I have 2 lists of numbers that can be different lengths, for example:
list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]
I need to iterate over these with the function:
final_list = []
for index in range(???):
if list1[index] < 0:
final_list.insert(0, list1[index])
elif list1[index] > 0:
final_list.insert(len(final_list), list1[index])
if list2[index] < 0:
final_list.insert(0, list2[index])
elif list2[index] > 0:
final_list.insert(len(final_list), list2[index])
return final_list
but can't figure out how to deal with the range as the shorter list will become "out of range" if I use the max length. Any thoughts on how to overcome this or how to change my function?
解决方案If the iterables are of uneven length, missing values are filled-in with fillvalue.
For your example lists, this will yield:
>>> import itertools
>>> list1 = [1, 2, -3, 4, 7]
>>> list2 = [4, -6, 3, -1]
>>> for combination in itertools.zip_longest(list1, list2):
print(combination)
(1, 4)
(2, -6)
(-3, 3)
(4, -1)
(7, None)
If you only want to use as many values as are present in both lists, use the built-in zip():
The iterator stops when the shortest input iterable is exhausted.
>>> for combination in zip(list1, list2):
print(combination)
(1, 4)
(2, -6)
(-3, 3)
(4, -1)