简体   繁体   English

使用2个变量遍历Python列表

[英]Loop through Python list with 2 variables

In JavaScript, I can use two (2) pointers to get the values from a list at the beginning and end and then increment/decrement the pointers to continue. 在JavaScript中,我可以使用两(2)个指针从开头和结尾的列表中获取值,然后递增/递减指针以继续。 For example: 例如:

for (let i = 0, j = list.length - 1; i < j; i++, j--) {
    console.log(i, j);
}

How would I be able to accomplish the same in Python? 我怎样才能在Python中完成同样的工作? I know that I can get the current index by doing: 我知道我可以通过以下方式获取当前索引:

for index in enumerate(list):
    print(index)

But how could I also initialize another pointer to start from the end? 但是我怎么能初始化另一个指针从头开始呢?

I assume that you want a solution that can do anything with the indices, not just print them out. 我假设您需要一个可以对索引执行任何操作的解决方案,而不仅仅是将它们打印出来。 Python's for loops have other strengths. Python的for循环还有其他优点。 So use a while loop. 所以使用while循环。

i = 0
j = len(alist)
while i < j:
    print(i, j)  # or console.log(i, j) or whatever you want here
    i += 1
    j -= 1

Here is something similar using zip , which is more pythonic. 这是使用zip类似的东西,更加pythonic。 Here I illustrate doing something other than just printing the indices. 在这里,我说明了除了打印索引之外的其他事情。

alist = [3, 1, 4, 1, 5, 9]
llen = len(alist)
for i, j in zip(range(llen // 2), range(llen - 1, -1, -1)):
    print(alist[i], alist[j])

But it is even more pythonic to ignore the indices and just use the items of the list, as in 但忽略指数并使用列表中的项目更加pythonic,如

alist = [3, 1, 4, 1, 5, 9]
llen = len(alist)
for u, v in zip(alist[:llen // 2], alist[::-1]):
    print(u, v)

Here's an example how you can do it. 这是一个如何做到这一点的例子。 Take second index as function of length minus index minus one: 取第二个索引作为长度减去索引减1的函数:

l = [1, 2, 3, 4]
for i, _ in enumerate(l):
    print(l[i], l[len(l)-i-1])

This will output 这将输出

(1, 4)
(2, 3)
(3, 2)
(4, 1)

Not printing indexes themselves, but you can print them, if you chose to do so. 不打印索引本身,但如果您选择这样做,则可以打印它们。

The most pythonic way is to use list comprehension. 最pythonic的方式是使用列表理解。

 In [9]: print([f'{i} {j}' for i, j in zip(named_list, reversed(named_list)) if i < j])
Out [9]: ['0 9', '1 8', '2 7', '3 6', '4 5', '5 4', '6 3', '7 2', '8 1', '9 0']

This list comprehension is shortcut for 这个列表理解是捷径

results = []
for i, j in zip (named_list, reversed(named_list)):
   if i >= j:
      break
   results.append((i,j))

I am sure you will prefer this: 我相信你会更喜欢这个:

for i in zip(alist, alist[::-1]):
    print(i) 
    # use i[0] and i[1] if you need both in different vars

You can use i[0] and i[1] to access variable separately. 您可以使用i [0]和i [1]分别访问变量。

Output: 输出:

(1, 4)
(2, 3)
(3, 2)
(4, 1)

If you want two index lists, the one starting from lower to higher and the other is inverse, range() function is pretty much there to help. 如果你想要两个索引列表,一个从低到高而另一个是反向的,那么range()函数几乎可以提供帮助。

For example if you have a list x = [1,2,3,4,5,6,7,8,9,10] then you can find both the indexes as: 例如,如果您有一个列表x = [1,2,3,4,5,6,7,8,9,10]那么您可以找到两个索引:

low_to_high_idx = list(range(0, len(x)-1))
high_to_low_idx = list(range(len(x)-1, -1, -1))

You can get both indexes then using zip() function 您可以使用zip()函数获取两个索引

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

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