如何遍历列表(如圆形)?

时间:2020-10-31 08:08:53

标签: python python-3.x

有什么办法可以让我像圈子一样遍历列表?一旦我到达列表的末尾,我会简单地回到第一个数字吗?

我尝试执行pop和append方法

lst = [1, 2, 3, 4, 5]
lst2 = lst.pop(0)
lst2 = lst2.append(lst[0])

是否有更好的方法?我不允许将导入作为限制的一部分。

4 个答案:

答案 0 :(得分:1)

使用嵌套在for循环中的while循环。

while True:
    for item in lst:
        # do something with item

答案 1 :(得分:1)

使用带有while和嵌套的生成器:

def cycle(myList):
    while True:
        for x in myList:
            yield x

并像这样循环:

for item in cycle(lst):
  # do something with item

答案 2 :(得分:0)

我希望这会有所帮助: 最后,它会吐出“递归错误”

lst = [1,2,3,4,5]

def fun(X):
    ls1 = []
    for itm in X:
        ls1.append(itm)
        if itm == X[-1]:
           fun(ls1)

答案 3 :(得分:0)

在索引列表时使用模数(%)运算符:

lst = [1, 2, 3, 4, 5]
FOREVER = 10                   # The number of times you want to print the
                               # list elements
for i in range(FOREVER):
    print (lst[i % len(lst)])  # Use the modulus operator to wrap-around

输出:

1
2
3
4
5
1
2
3
4
5