从某个元素开始循环浏览列表

发布于 2021-01-29 15:13:41

说我有一个清单:

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

我该怎么做?

关注者
0
被浏览
51
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    查看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]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看