遍历两个具有不同长度的列表

编程入门 行业动态 更新时间:2024-10-05 23:18:48
本文介绍了遍历两个具有不同长度的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

更多推荐

遍历两个具有不同长度的列表

本文发布于:2023-11-29 15:34:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646809.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:遍历   长度   两个   列表

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!