Python collections.Counter seems to break the original list

左心房为你撑大大i 提交于 2021-02-10 11:56:32

问题


Code:

sortedgroups = sorted(metagroups, key=lambda group: group[-1])
categories = map(operator.itemgetter(-1), sortedgroups)
categorycounts = collections.Counter(categories)

print('Writing output files')

with open('report.txt', 'a+') as f:
    for category in categories:
        f.write(category + '\n')

So this code works if I comment out:

categorycounts = collections.Counter(categories)

The for loop seems to break if I try to count the amounts of same strings in the categories list. Does collections.Counter() modify the original categories object?


回答1:


You seem to be using Python 3.

map now returns an iterator. collections.Counter(categories) exhausts the iterator, just like list(m) in the example below

In [3]: m = map(bool, [1, 2, 3, 4])

In [4]: list(m)
Out[4]: [True, True, True, True]

In [5]: list(m)
Out[5]: []

The solution is to build a sequence before calling collections.Counter. For example, a list can be constructed using either list:

categories = list(map(operator.itemgetter(-1), sortedgroups))

or list comprehension:

categories = [x[-1] for x in sortedgroups]


来源:https://stackoverflow.com/questions/32220180/python-collections-counter-seems-to-break-the-original-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!