问题
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.
So, given something like this
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))]
]
I would like to to
for sources_with_their_factors in MAGIC_HERE(a):
print(sources_with_their_factors)
and get
((1,11,21), (101,111,121))
((2,12,22), (102,112,122))
…
I tried
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.
回答1:
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))
...
回答2:
Why not just use indexes?
for i in range(len(a[0][0])):
tupA = (a[0][0][i], a[0][1][i], a[0][2][i])
tupB = (a[1][0][i], a[1][1][i], a[1][2][i])
print((tupA, tupB))
EDIT: this is a simple way - the way I ( a simpleton ) would do it. zip will be much more elegant and effective.
来源:https://stackoverflow.com/questions/54633091/iterator-of-list-of-list-of-iterables