在python中组合列表

2024-05-20 20:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试合并2个列表,并希望形成组合。你知道吗

a = ['ibm','dell']
b = ['strength','weekness']

我想形成像['ibm strength','ibm weekness','dell strength','dell weakness']这样的组合。你知道吗

我试着用zip或者连接列表。我也使用了itertools,但它没有给我想要的输出。请帮忙。你知道吗

a = ['ibm','dell']
b = ['strength','weekness']
c = a + b
itertools.combinations(c,2)
for a in a:
    for b in b:
        print a +b

Tags: in列表forzipibmstrengthdellprint
2条回答

你在找^{}。试试这个:

import itertools

a = ['ibm', 'dell']
b = ['strength', 'weakness']

[' '.join(x) for x in itertools.product(a, b)]
=> ['ibm strength', 'ibm weakness', 'dell strength', 'dell weakness']

要遍历结果,请不要忘记itertools.product()返回一个只能使用一次的迭代器。如果您以后需要它,请将其转换为一个列表(正如我在上面所做的,使用列表理解),并将结果存储在一个变量中,以备将来使用。例如:

lst = list(itertools.product(a, b))
for a, b in lst:
    print a, b

对于Cartesian product,需要itertools.product()而不是组合。你知道吗

嵌套for循环也可以工作:

for x in a:
    for y in b:
        c = a + b
        print(c)

相关问题 更多 >