简体   繁体   English

在Python中同时向后和向前迭代两个列表

[英]Iterate backwards and forwards over two lists at the same time in Python

I have two lists: 我有两个清单:

list1 = [2,1,0]
list2 = [0,1,2]

I have tried this one. 我已经试过了。

for i,j in zip(list1,list2):
    print (i,j) //This prints out 2 0, 1 1 and 0 2

But I want to print out 2 2, 1 1 and 0 0. So I have to loop the second loop backwards while I loop the first one forwards. 但是我想打印2 2、1 1和00。所以我必须将第二个循环向后循环,而将第一个循环向前循环。 I know how to do each of these in separate for loop , but I cannot figure out how to do this in one single for loop . 我知道如何在单独的for loop ,但是我无法弄清楚如何在单个for loop

You're looking for the reversed function. 您正在寻找reversed功能。

for i, j in zip(list1, reversed(list2):
    print(i, j)

Alternatively, depending on the data type, you can use fancy slicing . 另外,根据数据类型,您可以使用fancy slicing This generally works on data types that implement slicing (eg lists, tuples, numpy arrays), but won't work on a lot of other iterators. 这通常适用于实现切片的数据类型(例如,列表,元组,numpy数组),但不适用于许多其他迭代器。

for i, j in zip(list1, list2[::-1]):
    print(i, j)

The list2[::-1] slice means to slice the entire list with an increment of -1, which means that it will move backward through the list instead of forwards. list2[::-1] slice表示以-1为增量对整个列表进行切片,这意味着它将在列表中向后移动而不是向前移动。

Here's another option, which is very basic, but may get the job done: 这是另一个非常基本的选项,但可以完成工作:

for i,j in enumerate(list1):
    print j, list2[-i-1]

This will work as expected under the assumption both lists are the same length, otherwise, it will simply iterate for the number of elements in the first list. 在两个列表长度相同的前提下,这将按预期工作,否则,将仅迭代第一个列表中的元素数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM