从某个元素开始循环列表

时间:2012-01-20 11:30:07

标签: python list cycle

说我有一个清单:

l = [1, 2, 3, 4]

我想循环一下。通常,它会做这样的事情,

1, 2, 3, 4, 1, 2, 3, 4, 1, 2...

我希望能够在周期中的某个点开始,不一定是索引,但可能与元素匹配。假设我想从列表==4中的任何元素开始,然后输出将是

4, 1, 2, 3, 4, 1, 2, 3, 4, 1...

我该如何做到这一点?

7 个答案:

答案 0 :(得分:20)

查看itertools模块。它提供了所有必要的功能。

from itertools import cycle, islice, dropwhile

L = [1, 2, 3, 4]

cycled = cycle(L)  # cycle thorugh the list 'L'
skipped = dropwhile(lambda x: x != 4, cycled)  # drop the values until x==4
sliced = islice(skipped, None, 10)  # take the first 10 values

result = list(sliced)  # create a list from iterator
print(result)

输出:

[4, 1, 2, 3, 4, 1, 2, 3, 4, 1]

答案 1 :(得分:7)

使用算术mod运算符。假设您从位置k开始,那么k应该像这样更新:

k = (k + 1) % len(l)

如果你想从某个元素而不是索引开始,你总是可以像k = l.index(x)那样查找,其中x是所需的项目。

答案 2 :(得分:3)

当你可以通过几行自己做事时,我不是那么大的导入模块的粉丝。这是我没有进口的解决方案:

def cycle(my_list, start_at=None):
    start_at = 0 if start_at is None else my_list.index(start_at)
    while True:
        yield my_list[start_at]
        start_at = (start_at + 1) % len(my_list)

这将返回循环列表的(无限)迭代器。要获取循环中的下一个元素,必须使用next语句:

>>> it1 = cycle([101,102,103,104])
>>> next(it1), next(it1), next(it1), next(it1), next(it1)
(101, 102, 103, 104, 101) # and so on ...
>>> it1 = cycle([101,102,103,104], start_at=103)
>>> next(it1), next(it1), next(it1), next(it1), next(it1)
(103, 104, 101, 102, 103) # and so on ...

答案 3 :(得分:2)

import itertools as it
l = [1, 2, 3, 4]
list(it.islice(it.dropwhile(lambda x: x != 4, it.cycle(l)),  10))
# returns: [4, 1, 2, 3, 4, 1, 2, 3, 4, 1]

所以你想要的迭代器是:

it.dropwhile(lambda x: x != 4, it.cycle(l))

答案 4 :(得分:1)

嗯,http://docs.python.org/library/itertools.html#itertools.cycle没有这样的开始元素。

也许你只是开始循环并删除你不喜欢的第一个元素。

答案 5 :(得分:0)

另一个奇怪的选择是,可以向后完成循环列表。例如:

# Run this once
myList = ['foo', 'bar', 'baz', 'boom']
myItem = 'baz'

# Run this repeatedly to cycle through the list
if myItem in myList:
    myItem = myList[myList.index(myItem)-1]
    print myItem

答案 6 :(得分:0)

可以使用类似这样的东西:

def my_cycle(data, start=None):
  k = 0 if not start else start
  while True:
    yield data[k]
    k = (k + 1) % len(data)

然后运行:

for val in my_cycle([0,1,2,3], 2):
  print(val)

基本上与先前的答案之一相同。我不好。

相关问题