如何处理嵌套循环中的空列表?

发布于 2025-01-19 11:08:08 字数 640 浏览 2 评论 0原文

我正在寻找一种迭代两个列表的产品的方法,这些列表有时可以是空的。 本来要使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

天冷不及心凉 2025-01-26 11:08:08

将它们放在一个变量中并过滤它们以仅使用非空变量:

import itertools

lists = [1, 2], []

for i in itertools.product(*filter(bool, lists)):
    print(i)

或者如果将它们放在单独的变量中确实是您想要的:

import itertools

list1 = [1, 2]
list2 = []

for i in itertools.product(*filter(bool, (list1, list2))):
    print(i)

两者的输出:

(1,)
(2,)

Put them in one variable and filter them to use only the non-empty ones:

import itertools

lists = [1, 2], []

for i in itertools.product(*filter(bool, lists)):
    print(i)

Or if having them in separate variables is truly what you want:

import itertools

list1 = [1, 2]
list2 = []

for i in itertools.product(*filter(bool, (list1, list2))):
    print(i)

Output of both:

(1,)
(2,)
故人的歌 2025-01-26 11:08:08

一种方法是检查任何列表是否为空列表并提高了一定的价值,但这不是最优雅的解决方案。例如:

import itertools

list1 = [1, 2]
list2 = []

if len(list2) == 0:
    list2.append("")

for i, j in itertools.product(list1, list2):
    print(i, j)

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:

import itertools

list1 = [1, 2]
list2 = []

if len(list2) == 0:
    list2.append("")

for i, j in itertools.product(list1, list2):
    print(i, j)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文