python - 以相反顺序迭代 2 个不同长度的列表

标签 python list python-2.7

我有两个项目列表,我不知道它们的长度,但不必相同。我需要将他们的项目以相反的顺序成对添加到另一个列表中。因此 list1 中的最后一项与 list2 中的最后一项配对。仅当两个列表中的第一个项目的长度相同时才会配对。

我不知道如何在 Python 中做到这一点,而在其他语言中这很容易做到。这是我到目前为止所尝试过的,但它不起作用:

blocks = []
list = list1
if len(list2) > len(list1):
    list = list2
r_list1 = reversed(list1)
r_list2 = reversed(list2)

for i, not_used in enumerate(list):
    blocks.append([
        r_list1[i] if len(r_list1) > i else None,
        r_list2[i] if len(r_list2) > i else None,
    ])

最佳答案

使用itertools.izip_longest :

>>> import itertools
>>> lst1 = [1,2,3,4]
>>> lst2 = [5,6,7]

>>> itertools.izip_longest(reversed(lst1), reversed(lst2))
<itertools.izip_longest object at 0x0000000002D13228>

>>> list(itertools.izip_longest(reversed(lst1), reversed(lst2)))
[(4, 7), (3, 6), (2, 5), (1, None)]

>>> map(list, itertools.izip_longest(reversed(lst1), reversed(lst2)))
[[4, 7], [3, 6], [2, 5], [1, None]]

如果您需要另一个值而不是 None,请使用 fillvalue 关键字参数:

>>> list(itertools.izip_longest(reversed(lst1), reversed(lst2), fillvalue=999))
[(4, 7), (3, 6), (2, 5), (1, 999)]

关于python - 以相反顺序迭代 2 个不同长度的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21349115/

相关文章:

python - 填充在 Mongoengine 中,引用字段

python - 使用 ANTLR 在 Python 中解析时如何获取 AST 树而不是列表?

java - 当通过 For 循环返回 List 时,无法在 Java 中将 List 转换为 Map

Python:定义数字列表的方差

python - 如何检测嵌套列表的哪些元素发生了变化? (Python)

python - 为什么我的代码不根据字典解码加密字符串?

python - 使用Python中的生成器函数实现长除法

python cPickle.dumps 包含换行符

python-2.7 - 如何将 matplotlib ax range 设置为正值并围绕某个值进行镜像

python - 即使找到文件,也出现文件未找到错误