python - 如何在列表中循环更多次 python 中的列表大小?

标签 python list loops

我需要知道在 python 中是否存在允许我在列表中循环的次数多于列表中元素数的函数或 native 库。换句话说,当我感兴趣的索引大于列表大小时,下一个元素是列表的第一个。

例如,我有这个列表:

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__

关于python - 如何在列表中循环更多次 python 中的列表大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50033547/

相关文章:

c - 我试图获取数字的平均值并在用户按 -1 时退出代码,但它保持无限循环

python - 如何访问 GridSearchCV 中的 ColumnTransformer 元素

python - 使用 Perl 的 B::Concise 之类的东西转储 Python opttree?

java.util.ConcurrentModificationException : Unexpected List modification while multithreading?

python - 向 python 元组添加条目

c++ - 使用 GCC 优化 C/C++ 循环中的嵌套 if 语句

python - 'dataframe' 对象没有属性 'str' 问题

Python Coverage 说 A 行被覆盖,需要知道从哪里覆盖

list - 合并列表列表并循环返回

iphone - 将 URL(作为字符串)添加到数组时出现问题