迭代器列表的迭代器 [英] Iterator of list of list of iterables

查看:75
本文介绍了迭代器列表的迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想迭代Python3中的Iterables列表.

I would like to iterate of a list of list of Iterables in Python3.

换句话说,我有一个可迭代的矩阵,我想遍历并在每次迭代时都得到一个值矩阵.更具体地说,我有几个文件(行),它们有多个版本(列),我希望在每次迭代时,得到一个包含所有文件第一行的元组/矩阵,依此类推.

Stated differently, I have a matrix of iterables and I would like to loop through and get at each iteration a matrix of values. More concretely, I have several files (the rows) which have multiple versions of them (the columns) and I would like at each iteration, get a tuple/matrix containing the first line of all my files and so on.

所以,给定这样的东西

a = [
  [iter(range(1,10)), iter(range(11,20)), iter(range(21,30))],
  [iter(range(101,110)), iter(range(111,120)), iter(range(121,130))]
]

我想

for sources_with_their_factors in MAGIC_HERE(a):
  print(sources_with_their_factors)

并获得

((1,11,21), (101,111,121))
((2,12,22), (102,112,122))
…

我尝试了

for b in zip(zip(*zip(*a))):
    ...:     print(b)
    ...:
((<range_iterator object at 0x2b688d65b630>, <range_iterator object at 0x2b688d65b7e0>, <range_iterator object at 0x2b688d65b540>),)
((<range_iterator object at 0x2b688d65ba50>, <range_iterator object at 0x2b688d65b6f0>, <range_iterator object at 0x2b688d65b0c0>),)

但这并不是在重复我的范围.

But it isn’t iterating my ranges.

推荐答案

很显然,您可以将每个子列表中的迭代器一起zip在一起,只是缺少了如何将结果迭代器一起zip在一起.我将解压缩一个生成器表达式:

Obviously you can zip the iterators in each sublist together, you're just missing how to zip the resulting iterators together. I would unpack a generator expression:

for t in zip(*(zip(*l) for l in a)):
    print(t)

((1, 11, 21), (101, 111, 121))
((2, 12, 22), (102, 112, 122))
...

这篇关于迭代器列表的迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆