且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

重复数组中的值直到指定长度

更新时间:2023-02-18 10:12:24

您可以使用 itertools.cycle 重复遍历列表,并根据需要获取任意数量的值。

You can use itertools.cycle to iterate repeatedly over the list, and take as many values as you want.

from itertools import cycle

lst = [1, 2, 3, 4]
myiter = cycle(lst)
print([next(myiter) for _ in range(10)])


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

您也可以使用它来扩展列表(如果您追加了到最后,虽然您无法遍历它,但是删除项目是行不通的。)

You can also use it to extend the list (it doesn't matter if you append to the end while you are iterating over it, although removing items would not work).

from itertools import cycle

lst = [1, 2, 3, 4]
myiter = cycle(lst)
for _ in range(6):
    lst.append(next(myiter))
print(lst)


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