【问题标题】:How can the indexation of a list be made cyclic in python?如何在 python 中使列表的索引成为循环的?
【发布时间】:2014-04-03 15:08:15
【问题描述】:

如果我们有一个列表:

myList = [1,2,3,4,5]

使列表循环索引的pythonic方法是什么?这意味着我永远无法得到 indexError。而且我需要索引,因此我不能将cyclenext 一起使用
例如:

>>>myList[6]
2
>>>myList[-6]
5

【问题讨论】:

    标签: python list cycle


    【解决方案1】:

    你可以像这样使用模数运算符

    myList = [1, 2, 3, 4, 5]
    print myList[6  % len(myList)]
    # 2
    print myList[-6 % len(myList)]
    # 5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-07
      • 2021-02-07
      • 1970-01-01
      • 2014-01-28
      相关资源
      最近更新 更多