Python中的条件嵌套循环
我有一组不同的条件,可以用1、2或3个不同的子列表填充列表 我正在寻找一种方法来编写一个条件,该条件将运行:Python中的条件嵌套循环,python,python-3.x,loops,for-loop,Python,Python 3.x,Loops,For Loop,我有一组不同的条件,可以用1、2或3个不同的子列表填充列表 我正在寻找一种方法来编写一个条件,该条件将运行: 单个列表中元素的单个循环 两个子列表中元素的双循环 所有3个子列表中元素的三重循环 例如: list1 = ['UK', 'USA', 'Austria', 'Canada'] list2 = ['001', '001', '99', '1001', '009', '002'] list3 = [100, 200, 300, 500, 1000] list_total = [list1
list1 = ['UK', 'USA', 'Austria', 'Canada']
list2 = ['001', '001', '99', '1001', '009', '002']
list3 = [100, 200, 300, 500, 1000]
list_total = [list1, list2, list3]
if list2 and list3 or list_total[1] and list_total[2] are both None:
for elm in list1:
***do stuff***
if list2 or list_total[1] is None:
for elm1 in list1:
***maybe do stuff if I want***
for elm2 in list2:
***do stuff***
if all lists or list_total[1] and list_total[2] and list_total[3] are all not None:
for elm1 in list1:
for elm2 in list2:
***maybe do stuff if I want***
for elm3 in list3:
***do stuff***
有没有办法做到这一点
我不能只是迭代列表中的所有元素,从中“创建”一个for循环。您需要的可能是
itertools.product
代码示例:
import itertools
list1 = ['UK', 'USA', 'Austria', 'Canada']
list2 = ['001', '001', '99', '1001', '009', '002']
# list3 = [100, 200, 300, 500, 1000]
list3 = None
list_total = [list1, list2, list3]
list_total = [l for l in list_total if l is not None]
for t in itertools.product(*list_total):
print(t)
希望你能从这里出发