简体   繁体   English

生成清单的生成器

[英]Generator to Yield a List

I have three lists of lists, and I'm trying to write a generator function to help me package up values in the same index. 我有三个列表列表,并且试图编写一个生成器函数来帮助我将值打包在同一索引中。

So my lists: 所以我的清单:

list1 = [[1, 2, 3], [2, 3, 4],...]
list2 = [[4, 5, 6], [5, 6, 7],...]
list3 = [[8, 9, 10], [9, 10, 11],...]

My desired output: 我想要的输出:

result1 = [[1, 4, 8], [2, 5, 9],...]
result2 = [[2, 5, 9], [3, 6, 10],...]
result3 = [[3, 6, 10], [4, 7, 11],...]

My attempt: 我的尝试:

def bundle(x, y, z, index):
    for row in x, y, z:
        for item in row[index]:
            yield list(item)

I keep getting float is not iterable errors. 我一直在浮动不是可迭代的错误。 If i modify it slightly: 如果我稍加修改:

def bundle(x, y, z, index):
    for row in x, y, z:
        for item in row:
            yield item[index]

I get the values I want as one large sequence, but I would prefer to keep them grouped in a nested style. 我得到的值是一个较大的序列,但我希望将它们按嵌套样式分组。

One way to do this is by a repeated application of zip() : 一种方法是重复使用zip()

res1, res2, res3 = zip(*(zip(*x) for x in zip(list1, list2, list3)))

This uses zip(list1, list2, list3) to create a sequence of matrices, zip(*x) to transpose each of this matrices, and a final zip() to unpack to the three resulting sequences. 它使用zip(list1, list2, list3)创建一个矩阵序列,使用zip(*x)转置每个矩阵,最后使用zip()解压缩为三个结果序列。 (I don't think this approach is very efficient.) (我认为这种方法不是非常有效。)

If you're dealing with numeric values then you could use numpy's transposition method to achieve what you want: 如果要处理数字值,则可以使用numpy的转置方法来实现所需的功能:

import numpy
numpy.array([list1,list2, list3]).T

If you're dealing with large lists, a custom, fully lazy approach would be the following: 如果要处理大型列表,则可以使用以下自定义的完全惰性方法:

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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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