I have a list that have different length in each dimension like below:
list1=[[2,3,4],[1],[77,8,27,12],[25,15]]
and I have another list with the same number of element like:
list2=[a,b,c,d,e,f,g,h,i,j]
I want to reshape my list2 as list1 and to process two lists together in a for loop.
Here's a kind of cute way.
list1 = [[2,3,4],[1],[77,8,27,12],[25,15]]
list2 = list("abcdefghij")
list2_iterator = iter(list2)
list2_reshaped = [[next(list2_iterator) for _ in sublist] for sublist in list1]
print(list2_reshaped)
Out: [['a', 'b', 'c'], ['d'], ['e', 'f', 'g', 'h'], ['i', 'j']]
I don't know if it's possible with pure comprehensions.
Flattening list1 to match list2 is easy—either just use itertools.chain.from_iterable(list))
, or flat1 = [elem for sublist in list1 for elem in sublist]
, or the various other options in this question.
Going the other way is a bit more complicated. But, rather than looking for a one-liner, let's just do it explicitly: Create an iterator over list2
, and pull elements off it as needed:
def zipstructured(list1, list2):
iter2 = iter(list2)
for sublist1 in list1:
sublist2 = list(itertools.islice(iter2, len(sublist1)))
yield sublist1, sublist2
Now you can just do this:
>>> list1=[[2,3,4],[1],[77,8,27,12],[25,15]]
>>> list2=['a','b','c','d','e','f','g','h','i','j']
>>> for sub1, sub2 in zipstructured(list1, list2):
... print(sub1, sub2)
[2, 3, 4] ['a', 'b', 'c']
[1] ['d']
[77, 8, 27, 12] ['e', 'f', 'g', 'h']
[25, 15] ['i', 'j']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With