python - 生成列表的生成器

标签 python generator

我有三个列表列表,我正在尝试编写一个生成器函数来帮助我将值打包到同一个索引中。

所以我的 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/

相关文章:

python - 将换行符和 XML 标签替换为 ','

python - 具有稀疏矩阵的决策树分类器

python - 分形地形/高度图生成

python - 从其中包含 return <value> 语句的生成器中产生

python - 快速打开和关闭csv?

python - AppEngine MapReduce 如何在使用数据存储输入读取器时过滤 StructuredProperty?

python - 多索引 Pandas 数据框和 .diff()

python - 解析生成器 Python 2

php - Zend Framework 的模型和后端接口(interface)生成器

oracle - 编写一个oracle存储过程以生成唯一的序列号?