千家信息网

python如何根据给定的KEY分组

发表于:2025-02-01 作者:千家信息网编辑
千家信息网最后更新 2025年02月01日,小编给大家分享一下python如何根据给定的KEY分组,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!根据给定的KEY分组(
千家信息网最后更新 2025年02月01日python如何根据给定的KEY分组

小编给大家分享一下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 noneyoung myope no normal softyoung myope yes reduced noneyoung myope yes normal hardyoung hypermetrope no reduced noneyoung hypermetrope no normal softyoung hypermetrope yes reduced noneyoung hypermetrope yes normal hardpre-presbyopic myope no reduced nonepre-presbyopic myope no normal softpre-presbyopic myope yes reduced nonepre-presbyopic myope yes normal hardpre-presbyopic hypermetrope no reduced nonepre-presbyopic hypermetrope no normal softpre-presbyopic hypermetrope yes reduced nonepre-presbyopic hypermetrope yes normal nonepresbyopic myope no reduced nonepresbyopic myope no normal nonepresbyopic myope yes reduced nonepresbyopic myope yes normal hardpresbyopic hypermetrope no reduced nonepresbyopic hypermetrope no normal softpresbyopic hypermetrope yes reduced nonepresbyopic 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: hardyoung myope yes normal hardyoung hypermetrope yes normal hardpre-presbyopic myope yes normal hardpresbyopic myope yes normal hard-----------Group: noneyoung myope no reduced noneyoung myope yes reduced noneyoung hypermetrope no reduced noneyoung hypermetrope yes reduced nonepre-presbyopic myope no reduced nonepre-presbyopic myope yes reduced nonepre-presbyopic hypermetrope no reduced nonepre-presbyopic hypermetrope yes reduced nonepre-presbyopic hypermetrope yes normal nonepresbyopic myope no reduced nonepresbyopic myope no normal nonepresbyopic myope yes reduced nonepresbyopic hypermetrope no reduced nonepresbyopic hypermetrope yes reduced nonepresbyopic hypermetrope yes normal none-----------Group: softyoung myope no normal softyoung hypermetrope no normal softpre-presbyopic myope no normal softpre-presbyopic hypermetrope no normal softpresbyopic hypermetrope no normal soft

以上是"python如何根据给定的KEY分组"这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!

0