python - 遍历两个不同长度的列表

标签 python list loops

我有 2 个长度不同的数字列表,例如:

list1 = [1, 2, -3, 4, 7]
list2 = [4, -6, 3, -1]

我需要用函数迭代这些:

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 长度,较短的列表将变得“超出范围”。关于如何克服这个问题或如何改变我的功能有什么想法吗?

最佳答案

itertools.zip_longest(*iterables, fillvalue=None)将为您完成这项工作:

If the iterables are of uneven length, missing values are filled-in with fillvalue.

对于您的示例列表,这将产生:

>>> 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() :

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)

关于python - 遍历两个不同长度的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44000727/

相关文章:

python - 循环中的可调用变量

python - 如何在Python中从另一个字符串中检测一个字符串的重复元素?

python - 在 Python 中获取列表的下一个元素

python - 如何比较两个列表?

javascript - 当条件变量(全局变量)在 javascript 中发生变化时停止循环

python - Python 中 Dataframe 中每一行之间的余弦相似度

python - 如何限制 Django 模型中数值字段的最大值?

java - 将字符串分配给字符串数组

python - Django:插入时多对多关系的新记录

python - 按字母顺序对单元格文本排序