gpt4 book ai didi

python - Python 中的条件嵌套循环

转载 作者:行者123 更新时间:2023-12-01 00:48:24 26 4
gpt4 key购买 nike

我有一组不同的条件,将使用 1、2 或 3 个不同的子列表填充列表。

我正在寻找一种方法来编写将运行的条件:

  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, 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)

希望你能离开这里。

关于python - Python 中的条件嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56763370/

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