遍历两个不同长度的列表

新手上路,请多包涵

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

原文由 pmit 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 763
1 个回答

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

如果可迭代对象的长度不均匀,则使用 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()

当最短的输入迭代耗尽时,迭代器停止。

 >>> for combination in zip(list1, list2):
    print(combination)

(1, 4)
(2, -6)
(-3, 3)
(4, -1)

原文由 Christian König 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏