Python collections.Counter似乎打破了原来的清单 [英] Python collections.Counter seems to break the original list

查看:49
本文介绍了Python collections.Counter似乎打破了原来的清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码:

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)

如果我尝试计算类别列表中相同字符串的数量,则for循环似乎中断. collections.Counter()是否会修改原始类别对象?

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?

推荐答案

您似乎正在使用Python 3.

You seem to be using Python 3.

map 现在返回一个迭代器. collections.Counter(categories)耗尽迭代器,就像下面示例中的 list(m)一样

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]: []

解决方案是构建序列,然后调用 collections.Counter .例如,可以使用 list :

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))

列表理解:

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

这篇关于Python collections.Counter似乎打破了原来的清单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆