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

标签 python-2.7

我有一个像下面的 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/

相关文章:

python - 为什么 Python 将元组作为向量添加到列表理解中,但将它们与 '+' 运算符连接起来?

python - 如何在sklearn grid search中使用log loss

python - 如何检测一个二维数组是否在另一个二维数组中?

python - Flask 测试带有自定义 header 的放置请求

python - Python中graphviz中的不同颜色边缘

python - 我可以在我的win10机器上同时安装python 2.7和3.5吗?

python-3.x - 如何让 virtualenv 运行 Python 3 而不是 Python 2.7?

arrays - 使用 Pandas 数据框进行数据操作

python - 为什么我没有得到列表

python-2.7 - 如何在 scrapy 中连接 XPath