当前位置: 首页 > 工具软件 > tootgroup.py > 使用案例 >

python itertool.groupby使用误点!

林俊英
2023-12-01

使用误点一:

误以为 groupby是按照key进行分组的:

例子

from random import choice
lst = [ Student(choice(['M','F']),choice(range(10,100))) for i in range(20)]
for k,items in itertools.groupby(lst,lambda x:x.sex):
    print k
    for x in items:
        print x
    print "-" * 20
</pre><p></p><p>输出结果:</p>FF:27F:44F:52--------------------MM:65--------------------FF:99--------------------MM:29--------------------FF:90F:20--------------------MM:63--------------------FF:93--------------------MM:53M:62M:74--------------------FF:59--------------------MM:50--------------------FF:42--------------------MM:82M:72--------------------FF:61F:86--------------------<p>从这里可以看出, groupby 的行为表现像uniq一样根据连续值来分组的,因此对想按照分组的key进行排序就可以达到原先的效果了</p><p></p><pre name="code" class="html">lst = sorted(lst,key=lambda x:x.sex)
for k,items in itertools.groupby(lst,lambda x:x.sex):
    print k
    for x in items:
        print x
    print "-" * 20

结果

F
F:27
F:44
F:52
F:99
F:90
F:20
F:93
F:59
F:42
F:61
F:86
--------------------
M
M:65
M:29
M:63
M:53
M:62
M:74
M:50
M:82
M:72
--------------------

参考:

https://docs.python.org/2/library/itertools.html?highlight=itertools#module-itertools

 类似资料: