在python中合并列表 [英] Combining lists in python

查看:53
本文介绍了在python中合并列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并两个列表,并希望形成组合.

I am trying to combine 2 lists and want to form combinations.

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

我想形成['ibm strength','ibm weekness','dell strength','dell weakness']之类的组合.

我尝试使用zip或连接列表.我也使用过itertools,但它没有给我想要的输出.请帮忙.

I tried to use zip or concatenated the lists. I also used itertools but it doesn't give me desired output. Please help.

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

推荐答案

您正在寻找 product() .试试这个:

You're looking for product(). Try this:

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()返回一个只能重复使用一次的 iterator .如果您以后需要它,请将其转换为列表(如我上面所做的那样,使用列表推导),并将结果存储在变量中,以备将来使用.例如:

To loop over the results don't forget that itertools.product() returns an iterator that can be consumed only once. If you need it at a later time, convert it into a list (as I did above, using a list comprehension) and store the result in a variable, for future use. For example:

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

这篇关于在python中合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆