从某个元素开始循环浏览列表 [英] Cycle through list starting at a certain element

查看:126
本文介绍了从某个元素开始循环浏览列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个列表:

l = [1, 2, 3, 4]

我想循环浏览.通常,它会执行类似的操作

And I want to cycle through it. Normally, it would do something like this,

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

我希望能够从循环中的某个点开始,不一定是索引,而是可能匹配一个元素.假设我想从列表==4中的任何元素开始,那么输出将是

I want to be able to start at a certain point in the cycle, not necessarily an index, but perhaps matching an element. Say I wanted to start at whatever element in the list ==4, then the output would be,

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

我该怎么做?

推荐答案

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

Look at itertools module. It provides all the necessary functionality.

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]

这篇关于从某个元素开始循环浏览列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆