遍历两个具有不同长度的列表 [英] Iterate over two lists with different lengths

查看:454
本文介绍了遍历两个具有不同长度的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有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)


如果您只想使用列表中存在的尽可能多的值,请使用内置的


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)

这篇关于遍历两个具有不同长度的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆