gpt4 book ai didi

python-2.7 - 循环选择列表元素

转载 作者:行者123 更新时间:2023-12-04 16:58:42 25 4
gpt4 key购买 nike

我有一个像下面的 list

list1 = [cont1,cont2,cont4,cont5]

如何在python中实现循环逻辑以选择列表中的元素,
每次我尝试访问元素

最佳答案

我建议使用 itertools.cycle

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.



用法示例:
seq = [1,2,3,4]
round_robin = itertools.cycle(seq)

assert round_robin.next() == 1
assert round_robin.next() == 2
assert round_robin.next() == 3
assert round_robin.next() == 4
assert round_robin.next() == 1
assert round_robin.next() == 2
assert round_robin.next() == 3
assert round_robin.next() == 4

关于python-2.7 - 循环选择列表元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38251174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com