我在这里不会 Select 使用Pythonzip
作为解决方案,因为需要连接两个数组才能得到循环移位的数组(单独的Slice不能循环移位).但是,我要做的只是遍历反转列表中的所有元素,并通过它的索引获得下一个值,如下所示:
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)
Edit:
使用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的内置list方法,您可能应该将其命名为lst
或类似的名称.