本文介绍了在Python中使用多个列表进行循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找解决问题的方法.目前,我有两个元素列表:
I'm looking for solution to my problem. At the moment I have two list of elements:
column_width = ["3", "3", "6", "8", "4", "4", "4", "4"]
fade = ["100", "200", "300"]
我要实现的是创建for循环,该循环将为我提供以下输出:
What I want to achieve is to create for loop which wil give me following output:
column-3-fade-100
column-3-fade-200
column-6-fade-300
column-8-fade-100
column-4-fade-200
...
嵌套循环对我不起作用
for i in fade:
for c in column_width_a:
print("column-{0}-fade-{1}".format(c, i))
还有其他方法可以生成此输出吗?
Is there any other way to generate this output?
推荐答案
这是使用 itertools.cycle
.
例如:
from itertools import cycle
column_width = ["3", "3", "6", "8", "4", "4", "4", "4"]
fade = cycle(["100", "200", "300"])
for i in column_width:
print("column-{}-fade-{}".format(i, next(fade)))
输出:
column-3-fade-100
column-3-fade-200
column-6-fade-300
column-8-fade-100
column-4-fade-200
column-4-fade-300
column-4-fade-100
column-4-fade-200
这篇关于在Python中使用多个列表进行循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!