如何处理嵌套循环中的空列表?
我正在寻找一种迭代两个列表的产品的方法,这些列表有时可以是空的。 本来要使用itertools.product
import itertools
list1 = [1, 2]
list2 = ['a', 'b']
for i, j in itertools.product(list1, list2):
print(i, j)
。
1 a
1 b
2 a
2 b
我 但是,当其中一个列表为空时,循环不会打印任何东西:
list1 = [1, 2]
list2 = []
for i, j in itertools.product(list1, list2):
print(i, j)
而我希望它的行为好像只有一个列表。因此,使用Itertools,请执行相当于:
for i in itertools.product(list1):
print(i)
它可以返回的等同:
(1,)
(2,)
我可以将其放入长时间的IF语句中,但是我正在寻找一个简单的调整,如果列表数量增加,可以轻松扩展。感谢您的帮助。
I am looking for a way to iterate through the product of two lists that can sometimes be empty.
I was going to use itertools.product for that, so it would look like this:
import itertools
list1 = [1, 2]
list2 = ['a', 'b']
for i, j in itertools.product(list1, list2):
print(i, j)
We would get:
1 a
1 b
2 a
2 b
And that's what I expect. But when one of the lists is empty, the loop won't print anything:
list1 = [1, 2]
list2 = []
for i, j in itertools.product(list1, list2):
print(i, j)
Whereas I would like it to behave as if there was just one list. So, using itertools, do the equivalent of:
for i in itertools.product(list1):
print(i)
which would have returned:
(1,)
(2,)
I could put this into a long if statement, but I am looking for a simple tweak that would easily scale if the number of lists increased. Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将它们放在一个变量中并过滤它们以仅使用非空变量:
或者如果将它们放在单独的变量中确实是您想要的:
两者的输出:
Put them in one variable and filter them to use only the non-empty ones:
Or if having them in separate variables is truly what you want:
Output of both:
一种方法是检查任何列表是否为空列表并提高了一定的价值,但这不是最优雅的解决方案。例如:
One way of doing it would be checking if any of the lists is empty and putting in some value, but this is not the most elegant solution. For example: