打印列表中的当前元素和下一个元素,但顺序相反



给定一个lst = ["one", "two", "three"],我想打印当前元素及其下一个元素,但顺序相反。即:

three one
two three
one two

我的脚本打印当前和下一个元素,但不是按相反的顺序:

# It prints:
# one two
# two three
for curr, nxt in zip(lst, lst[1:]):
print(curr, nxt)
  • 如何编辑脚本以实现目标

我尝试了以下操作:

# It prints:
# three one
for curr, nxt in zip(lst[-1:], lst):
print(curr, nxt)

但它只给了我一个结果。

Python的zip不是我在这里想要的解决方案,因为你需要连接两个数组才能得到循环移位的数组(单独的切片不能循环移位(。然而,我要做的只是简单地遍历反向列表中的所有元素,并通过其索引获得下一个值,如下所示:

list = ["one", "two", "three"]
for i, curr in enumerate(list[::-1]): # enumerate gives you a generator of (index, value)
nxt = list[-i] # list[-i-1] would be the current value, so -i would be the next one
print(curr, nxt)

编辑:使用list[::-1]的速度比您通常想要的稍慢,因为它会遍历列表一次以反转它,然后再遍历一次。更好的解决方案是:

list = ["one", "two", "three"]
for i in range(len(list)-1, -1, -1):
curr = list[i]
nxt = list[len(list) - i - 1] # list[i+1] would not work as it would be index out of range, but this way it overflows to the negative side, which python allows.
print(curr, nxt)

但是,如果您确实希望使用zip,则需要执行以下操作:

list = ["one", "two", "three"]
for curr, nxt in zip(list[::-1], [list[0]] + list[:0:-1]):
print(curr, nxt)

您还应该注意,将变量命名为list不是一个好主意,因为您可能会对python的内置列表方法进行阴影处理,您可能应该将其命名为lst或类似的名称。

您可以迭代反向索引,该索引将指向当前项目,并且您可以根据列表的长度取索引的模,这将指向下一个项目

for i in range(len(lst), 0, -1):
print(lst[i-1], lst[i%len(lst)])

# output:  
three one
two three
one two

假设我正确理解了您的问题,如果索引超过size of list - 1%运算符将有助于找到下一个元素。

  • 从索引size-1循环到0
  • 下一个元素就是简单的i+1。然而,为了处理i+1超过列表边界的情况,我们可以使用(i+1)%size来";重新启动索引">
lst = ["one", "two", "three"]
size= len(lst)
# loop starting at index (size-1) and ending at index  0
for i in range(size-1,-1,-1): 
currentElement = lst[i]
nextElement = lst[(i+1)%size] 
print(currentElement, nextElement)

输出:

three one
two three
one two

我想你想要这个。。

a = ["one", "two", "three"] 
a.append(a[0])
a.reverse()
for curr, nxt in zip(a, a[1:]):
print(nxt, curr)

此外,强烈建议避免使用关键字list作为变量名。

最新更新