【问题标题】:How to loop in a list more times that list size in python?python - 如何在列表中循环更多倍于python中的列表大小?
【发布时间】:2018-10-06 14:18:18
【问题描述】:

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

例如,我有这个列表:

abc = ['a', 'b', 'c', 'd', 'e' ]

所以,如果我有一个值为 10 的参数,则结果是 'a'。如果值为 18 的参数是 'd'。

谢谢!

问候!

【问题讨论】:

  • 使用模运算符。
  • 您可以使用 itertools 模块中的函数 cycle(seq) 从您的 abc 数组创建无限序列,然后您可以使用同一模块中的 islice(seq, count) 函数在某个点剪切此序列。

标签: python list loops


【解决方案1】:

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'

【讨论】:

    【解决方案2】:

    最简单的:用模包装索引

    >>> 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__

    【讨论】:

    • abc[18:20] 怎么样? :P
    猜你喜欢
    • 1970-01-01
    • 2019-04-29
    • 2021-02-24
    • 2020-05-29
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    相关资源
    最近更新 更多