【问题标题】:How to move from end of list, to start in Python's lists?如何从列表末尾移动到 Python 列表中?
【发布时间】:2019-09-15 19:33:55
【问题描述】:

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

例如我有一个列表:

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'

【问题讨论】:

  • 你的意思是list1[-2::-1] => ['y', 'd', 'c', 'b', 'a']
  • 不清楚你所说的“从ya”是什么意思; a 可以通过 list1[0] 获取。

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


【解决方案1】:

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

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

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

【讨论】:

    【解决方案2】:
    i = (j + 2) % n
    # where j is the index of 'y' 
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-22
        • 2021-10-01
        • 2023-03-17
        相关资源
        最近更新 更多