简体   繁体   中英

python itertools groupby return empty

I'm very confusing why result of itertools.groupby has converted into list, still return empty? But you can see the correct print result!

from itertools import groupby

sample = [['data', '8', '1', '14:05:00', '15:05:00', 'fall'], ['data', '8', '1', '14:45:00', '15:45:00', 'winter']]

arr= []

for i2,i in groupby(data, key=lambda x: x[5]):
    print(i2, list(i))
    arr.append(list(i))

print(arr)

Why arr is empty?

That's because Python iterator can only be iterated once .

For example:

def f():
    for i in range(5):
        yield i

i = f() # i is an iterator

list(i) # [1, 2, 3, 4, 5]
# i has been iterated once, now it's empty
list(i) # []

In your case i is an iterator, and it's been iterated in print , so removing the print or assign it to a variable before printing:

l = list(i)
print(i2, l)
arr.append(l)

should give you the expected result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM