我今天的python任务是学习itertools
模块,但不幸的是我被困在groupby
课程上。我知道它是如何工作的,但我似乎无法弄清楚为什么我不能store
一个迭代器供以后使用。
from random import randint, choice
from string import ascii_lowercase as letters
from itertools import *
alist = []
while len(alist) != 50:
alist.append((choice(letters),randint(1,10))) #tuples of random numbers and letters
alist.sort(key = lambda x: x[1])
unique = []
for key , group in groupby(alist, lambda x: x[1]):
unique.append((key,group))
for g in group: #here I can iterate over the grouper object
print g
for x in unique:
print "Special key is %d" % x[0]
for i in x[1]: #here i can't loop through iterator
print i
为什么我不能通过unique
的第二个循环中的石斑鱼对象?我只得到print "Special key is %d"
语句10次。