我有三个列表列表,我正在尝试编写一个生成器函数来帮助我将值打包到同一个索引中。
所以我的 list :
list1 = [[1, 2, 3], [2, 3, 4],...]
list2 = [[4, 5, 6], [5, 6, 7],...]
list3 = [[8, 9, 10], [9, 10, 11],...]
我想要的输出:
result1 = [[1, 4, 8], [2, 5, 9],...]
result2 = [[2, 5, 9], [3, 6, 10],...]
result3 = [[3, 6, 10], [4, 7, 11],...]
我的尝试:
def bundle(x, y, z, index):
for row in x, y, z:
for item in row[index]:
yield list(item)
我不断收到 float is not iterable 错误。如果我稍微修改一下:
def bundle(x, y, z, index):
for row in x, y, z:
for item in row:
yield item[index]
我得到了我想要的值作为一个大序列,但我更愿意将它们分组为嵌套样式。
最佳答案
如果您要处理大型列表,自定义的、完全懒惰的方法如下:
import itertools as it
def bundle(lists, index):
return ([b[index] for b in blocks] for blocks in it.izip(*lists))
print list(bundle([[[1, 2, 3], [2, 3, 4]],
[[4, 5, 6], [5, 6, 7]],
[[8, 9, 10], [9, 10, 11]]],
0))
# => [[1, 4, 8], [2, 5, 9]]
关于python - 生成列表的生成器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9843574/