如何从列表末尾移动到Python列表的开头?

时间:2019-04-26 09:50:23

标签: python arrays python-3.x python-2.7 list

如何从列表的后两个值中获取列表的第一个值。

例如,我有一个列表:

list1 = ['a','b','c','d','y','z']
# I know that going from 'a' to 'y' is using negatives,
n = 0 - 2 
list1[n]
# This will give the value of 'y'

# but how do I do the opposite? 'y' to 'a' ?
# not fetching the values from 'y' to 'a', instead, traversing from 'y' to 'a'

3 个答案:

答案 0 :(得分:3)

如果您需要从'y''a'之间的值:

>>> list1[n::-1]
['y', 'd', 'c', 'b', 'a']

n-新列表的开始,-1-步骤

答案 1 :(得分:0)

i = (j + 2) % n
# where j is the index of 'y' 

答案 2 :(得分:0)

这应该可以解决问题。列表-2的开始和步骤-1

li = ['a','b','c','d','y','z']
print(li[-2::-1])
#['y', 'd', 'c', 'b', 'a']