在Python中是否有一个函数或本地库,允许我在列表中循环的次数超过列表元素的数量?换句话说,当我的感兴趣的索引大于列表大小时,下一个元素是列表的第一个元素。
例如,我有这个列表:
abc = ['a', 'b', 'c', 'd', 'e']
所以,如果我有一个值为10
的索引,结果将是'a'
。如果索引的值为18
,结果将是'd'
。
最简单的方法:使用模运算将索引包装起来。
>>> abc = ['a', 'b', 'c', 'd', 'e' ]
>>> abc[18 % len(abc)]
'd'
如果您想的话,可以将其封装在助手类中:
>>> class ModList(list):
... def __getitem__(self, item):
... if isinstance(item, slice):
... return super().__getitem__(item)
... return super().__getitem__(item % len(self))
...
>>> abc = ModList('abcde')
>>> abc[18]
'd'
>>> abc[-5]
'a'
>>> abc[-6]
'e'
你可能希望以类似的方式实现__setitem__
和__delitem__
。
itertools.cycle()
可以让你按顺序重复迭代一个列表。
from itertools import cycle
abc = ['a', 'b', 'c', 'd', 'e' ]
alfs = ''
for n, e in enumerate(cycle(abc)): # lazy enumeration?
alfs += e
if n >= 18: # must have stopping test to break infinite loop
break
alfs
Out[30]: 'abcdeabcdeabcdeabcd'
itertools
模块中的函数cycle(seq)
从你的abc
数组创建无限序列,然后你可以使用同一模块中的islice(seq, count)
函数在某个点上截断这个序列。 - Nikita Sivukhin