Swiffy
Swiffy

Reputation: 4693

Python collections.Counter seems to break the original list

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?

Upvotes: 2

Views: 101

Answers (1)

vaultah
vaultah

Reputation: 46533

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]

Upvotes: 5

Related Questions