假设我有一个列表:
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...
我如何才能做到这一点呢?
发布于 2012-01-20 19:50:04
看看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]
发布于 2012-01-20 19:35:46
使用算术mod
运算符。假设你从位置k
开始,那么k
应该像这样更新:
k = (k + 1) % len(l)
如果你想从某个元素开始,而不是从索引开始,你总是可以像k = l.index(x)
一样查找它,其中x是所需的项。
发布于 2012-01-20 21:51:01
我不是一个很喜欢导入模块的人,因为你只需要几行代码就可以完成你自己的事情。以下是我没有导入的解决方案:
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 ...
https://stackoverflow.com/questions/8940737
复制相似问题