我正在尝试循环遍历包含许多迭代器的dict ...它们的大小是许多in,但它们是经过排序的。一个简单的例子如下所示:
t = { 'a': iter([1,1,1,2,2,3,3,4,6,7,7,7]),
'b': iter([2,2,2,3,3,4,6,6,6,7,7,7]),
'c': iter([1,1,1,4,4,6,6,7,7]),
'd': iter([1,1,1,3,3,3,7,7,7])
}我需要为本身是迭代器的每个唯一项生成一个dict (同样,因为每个分组的大小可能是to )。在这个例子中,我需要类似这样的东西:
{'a':iter([1,1,1]),
'b':iter(),
'c':iter([1,1,1]),
'd':iter([1,1,1])
}
{'a':iter([2,2]),
'b':iter([2,2,2]),
'c':iter(),
'd':iter()
}
{'a':iter([3,3]),
'b':iter([3,3]),
'c':iter(),
'd':iter([3,3,3])
}
{'a':iter([4]),
'b':iter([4]),
'c':iter([4,4]),
'd':iter()
}没有5,所以我们就跳过它
{'a':iter([6]),
'b':iter([6,6,6]),
'c':iter([6,6]),
'd':iter()
}
{'a':iter([7,7,7]),
'b':iter([7,7,7]),
'c':iter([7,7]),
'd':iter([7,7,7])
}
StopIteration如果dict中缺少“空迭代器”也没问题。
我很确定我需要一台groupby,但我就是不能聚在一起。
谢谢你的帮助。
发布于 2011-03-18 23:11:01
到目前为止,我已经想出了这样的东西:
grouped = {}
for key, item in t.items():
grouped[key] = groupby(item):
current_items = {}
for key, val in grouped.items():
current_items[key] = val.next()
while current_items:
#find the first one
this_item = min((item for item, _ in current_items.items()))
outdict = {}
for key, (item, rows) in current_items.items():
if item == this_item:
#move the item to the output
outdict[key] = rows
try:
#advance the iterator
current_items[key] = grouped.next()
except StopIteration:
#must be out of items
current_items.pop(key)
grouped.pop(key)
yield outdict如果有人知道一种更具蟒蛇风格的方法,我将很高兴看到它。
https://stackoverflow.com/questions/5353596
复制相似问题