有没有办法循环遍历索引[重复]
Posted
技术标签:
【中文标题】有没有办法循环遍历索引[重复]【英文标题】:Is there a way to cycle through indexes [duplicate] 【发布时间】:2018-08-10 05:33:05 【问题描述】:list1 = [1,2,3,4]
如果我有list1
,如上图,最后一个值的索引是3
,但是有没有办法,如果我说list1[4]
,它会变成list1[0]
?
【问题讨论】:
试试list[-1]
。
没关系,我看不懂。
【参考方案1】:
你可以像这样对数学进行模运算:
代码:
list1 = [1, 2, 3, 4]
print(list1[4 % len(list1)])
结果:
1
【讨论】:
【参考方案2】:在您描述的情况下,我自己使用@StephenRauch 建议的方法。但是鉴于您添加了cycle
作为标签,您可能想知道存在itertools.cycle 这样的东西。
它返回一个迭代器,让您以循环方式永远循环遍历一个可迭代对象。我不知道你原来的问题,但你可能会发现它很有用。
import itertools
for i in itertools.cycle([1, 2, 3]):
# Do something
# 1, 2, 3, 1, 2, 3, 1, 2, 3, ...
但请注意退出条件,您可能会发现自己陷入了无限循环。
【讨论】:
【参考方案3】:您可以实现自己的类来执行此操作。
class CyclicList(list):
def __getitem__(self, index):
index = index % len(self) if isinstance(index, int) else index
return super().__getitem__(index)
cyclic_list = CyclicList([1, 2, 3, 4])
cyclic_list[4] # 1
特别是这将保留list
的所有其他行为,例如切片。
【讨论】:
以上是关于有没有办法循环遍历索引[重复]的主要内容,如果未能解决你的问题,请参考以下文章