如何从列表的后两个值中获取列表的第一个值。
例如,我有一个列表:
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'
答案 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']