我有2个数字列表,它们的长度可以不同,例如:
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但无法弄清楚如何处理该范围,因为如果使用max长度,则较短的列表将变得超出范围".关于如何克服这个问题或如何更改我的功能有什么想法吗?
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?
推荐答案itertools.zip_longest(*iterables, fillvalue=None) 将为您完成这项工作:
itertools.zip_longest(*iterables, fillvalue=None) will do the job for you:
如果可迭代项的长度不均匀,则用 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)
如果您只想使用和列表中存在的尽可能多的值,请使用内置的 zip() :
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)
更多推荐
遍历两个具有不同长度的列表
发布评论