Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

arrays - How to handle the situation if one iterator runs out while iterating through multiple lists in python using zip?

here is the code:-

array1 = [["a","b","c"] ,['e','f','g'] , ['i','j','k']]
array2 = ['d' , 'h']
array1 = [a+list(b) for a,b in zip(array1,array2)]
print(array1)

I want the desired output [["a","b","c", "d"] ,['e','f','g','h'] , ['i','j','k']] but the code gives the optput [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']].

This is happening because there is nothing to add to in array1[2], how to overcome this situation, I tried using a = [a+list(b) if b else a for a,b in zip(array1,array2)] but there was no change please help.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

zip ends prematurely in this case. You can use itertools.zip_longest instead, with a default fillvalue:

from itertools import zip_longest
print([a+b for a, b in zip_longest(array1, map(list, array2), fillvalue=[])])

Output:

[['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['i', 'j', 'k']]
>>> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...