小编给大家分享一下python如何根据给定的KEY分组,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
根据给定的KEY分组(itertools.groupby)
>>> from operator import itemgetter >>> import itertools >>> with open("contactlenses.csv", "r") as infile: ... data = [line.strip().split(",") for line in infile] ... >>> data = data[1:] >>> def print_data(rows): ... print " ".join(" ".join("{: <16}".format(s) for s in row) for row in rows) ... >>> print_data(data) young myope no reduced none young myope no normal soft young myope yes reduced none young myope yes normal hard young hypermetrope no reduced none young hypermetrope no normal soft young hypermetrope yes reduced none young hypermetrope yes normal hard pre-presbyopic myope no reduced none pre-presbyopic myope no normal soft pre-presbyopic myope yes reduced none pre-presbyopic myope yes normal hard pre-presbyopic hypermetrope no reduced none pre-presbyopic hypermetrope no normal soft pre-presbyopic hypermetrope yes reduced none pre-presbyopic hypermetrope yes normal none presbyopic myope no reduced none presbyopic myope no normal none presbyopic myope yes reduced none presbyopic myope yes normal hard presbyopic hypermetrope no reduced none presbyopic hypermetrope no normal soft presbyopic hypermetrope yes reduced none presbyopic hypermetrope yes normal none >>> data.sort(key=itemgetter(-1)) >>> for value, group in itertools.groupby(data, lambda r: r[-1]): ... print "-----------" ... print "Group: " + value ... print_data(group) ... ----------- Group: hard young myope yes normal hard young hypermetrope yes normal hard pre-presbyopic myope yes normal hard presbyopic myope yes normal hard ----------- Group: none young myope no reduced none young myope yes reduced none young hypermetrope no reduced none young hypermetrope yes reduced none pre-presbyopic myope no reduced none pre-presbyopic myope yes reduced none pre-presbyopic hypermetrope no reduced none pre-presbyopic hypermetrope yes reduced none pre-presbyopic hypermetrope yes normal none presbyopic myope no reduced none presbyopic myope no normal none presbyopic myope yes reduced none presbyopic hypermetrope no reduced none presbyopic hypermetrope yes reduced none presbyopic hypermetrope yes normal none ----------- Group: soft young myope no normal soft young hypermetrope no normal soft pre-presbyopic myope no normal soft pre-presbyopic hypermetrope no normal soft presbyopic hypermetrope no normal soft
以上是“python如何根据给定的KEY分组”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。