如果我存储嵌套 for 循环的输出,只打印循环的最后一个元素,但打印函数打印所有组合

If I store the output of nested for loop only the last elements of the loop are printed, but print function prints all the combinations

l1 = ['a','b']
l2 = ['c','d']
for x in l1:
   for y in l2:
       (a,b)=(x,y)

当我print(a,b)时,我得到的只是('b','d'),但是当我输入

这样的代码时
for x in l1:
   for y in l2:
       print((x,y))

打印了 l1l2 的所有可能组合。为什么会发生这种情况,我该如何处理?

下面的代码会给你所有可能的组合

l1 = ['a','b']
l2 = ['c','d']

for x in l1:
   for y in l2:
       (a, b) = (x, y)
       print(a, b)

另外,看看替代解决方案

from itertools import product


l1 = ['a','b']
l2 = ['c','d']

for (a, b) in product(l1, l2):
    print(a, b)

当您执行 (a,b)=(x,y) 时,它会将 a 的值设置为 x 的值,并将 b 的值设置为 y 的值。每次你 运行 通过 for 循环 ab 都会被缠住。另一方面,print 语句只是将这两个变量当时的值写入标准输出。如果您想存储这些值以供在 for 循环之后使用,我建议将它们附加到列表中。

l1 = ['a','b']
l2 = ['c','d']

combinations = []
for x in l1:
   for y in l2:
       combinations.append((x, y))

或者如 Roman Dryndik 的回答,您可以使用 product 函数。

简单的答案是当你做

l1 = ['a','b']
l2 = ['c','d']
for x in l1:
   for y in l2:
       (a,b)=(x,y)

我假设您是在 for 循环外调用 print 函数(您没有在粘贴的代码中显示调用它的位置)。在您的代码中, a 和 b 的值在每次迭代期间都会重新分配,因此当您在 for 循环之后调用它时,它只会打印上次分配给 a 和 b 的值。

当你这样做的时候:

l1 = ['a','b']
l2 = ['c','d']

for (a, b) in product(l1, l2):
    print(a, b)

您在 for 循环中调用了 print 函数。这意味着它在每次迭代中都会达到,因此它会在每次迭代中打印 a 和 b 的值。