python如何根据给定的KEY分组

python如何根据给定的KEY分组

小编给大家分享一下python如何根据给定的KEY分组,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

根据给定的KEY分组(itertools.groupby)

python如何根据给定的KEY分组

>>>fromoperatorimportitemgetter>>>importitertools>>>withopen("contactlenses.csv","r")asinfile:...data=[line.strip().split(",")forlineininfile]...>>>data=data[1:]>>>defprint_data(rows):...print"".join("".join("{:<16}".format(s)forsinrow)forrowinrows)...>>>print_data(data)youngmyopenoreducednoneyoungmyopenonormalsoftyoungmyopeyesreducednoneyoungmyopeyesnormalhardyounghypermetropenoreducednoneyounghypermetropenonormalsoftyounghypermetropeyesreducednoneyounghypermetropeyesnormalhardpre-presbyopicmyopenoreducednonepre-presbyopicmyopenonormalsoftpre-presbyopicmyopeyesreducednonepre-presbyopicmyopeyesnormalhardpre-presbyopichypermetropenoreducednonepre-presbyopichypermetropenonormalsoftpre-presbyopichypermetropeyesreducednonepre-presbyopichypermetropeyesnormalnonepresbyopicmyopenoreducednonepresbyopicmyopenonormalnonepresbyopicmyopeyesreducednonepresbyopicmyopeyesnormalhardpresbyopichypermetropenoreducednonepresbyopichypermetropenonormalsoftpresbyopichypermetropeyesreducednonepresbyopichypermetropeyesnormalnone>>>data.sort(key=itemgetter(-1))>>>forvalue,groupinitertools.groupby(data,lambdar:r[-1]):...print"-----------"...print"Group:"+value...print_data(group)...-----------Group:hardyoungmyopeyesnormalhardyounghypermetropeyesnormalhardpre-presbyopicmyopeyesnormalhardpresbyopicmyopeyesnormalhard-----------Group:noneyoungmyopenoreducednoneyoungmyopeyesreducednoneyounghypermetropenoreducednoneyounghypermetropeyesreducednonepre-presbyopicmyopenoreducednonepre-presbyopicmyopeyesreducednonepre-presbyopichypermetropenoreducednonepre-presbyopichypermetropeyesreducednonepre-presbyopichypermetropeyesnormalnonepresbyopicmyopenoreducednonepresbyopicmyopenonormalnonepresbyopicmyopeyesreducednonepresbyopichypermetropenoreducednonepresbyopichypermetropeyesreducednonepresbyopichypermetropeyesnormalnone-----------Group:softyoungmyopenonormalsoftyounghypermetropenonormalsoftpre-presbyopicmyopenonormalsoftpre-presbyopichypermetropenonormalsoftpresbyopichypermetropenonormalsoft

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

发布于 2022-03-19 21:11:29
收藏
分享
海报
0 条评论
27
上一篇:css如何实现黑白图像 下一篇:python如何链接可遍历对象
目录

    推荐阅读

    0 条评论

    本站已关闭游客评论,请登录或者注册后再评论吧~

    忘记密码?

    图形验证码