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