我如何一起加入2个列表?
让我们说:
list1 = ['hi', 'state', 'California', 'usa']
list2 = ['moon', 'sun', 'hi', 'flower']
并且输出会将单词连接在一起,排除包含相同单词的单词,例如'hi hi',如下所示:
['hi moon', 'hi sun', ' hi flower', 'state moon', 'state hi', 'state flower'] ...eetc..
答案 0 :(得分:3)
使用itertools.product()
,然后过滤掉相同的任何对:
from itertools import product
[' '.join([a, b]) for a, b in product(list1, list2) if a != b]
演示:
>>> from pprint import pprint
>>> from itertools import product
>>> list1 = ['hi', 'state', 'California', 'usa']
>>> list2 = ['moon', 'sun', 'hi', 'flower']
>>> [' '.join([a, b]) for a, b in product(list1, list2) if a != b]
['hi moon', 'hi sun', 'hi flower', 'state moon', 'state sun', 'state hi', 'state flower', 'California moon', 'California sun', 'California hi', 'California flower', 'usa moon', 'usa sun', 'usa hi', 'usa flower']
>>> pprint(_)
['hi moon',
'hi sun',
'hi flower',
'state moon',
'state sun',
'state hi',
'state flower',
'California moon',
'California sun',
'California hi',
'California flower',
'usa moon',
'usa sun',
'usa hi',
'usa flower']
答案 1 :(得分:3)
迭代列表解析中的每个列表。在这种情况下,我并不需要product
:
>>> list1 = ['hi', 'state', 'California', 'usa']
>>> list2 = ['moon', 'sun', 'hi', 'flower']
>>> [a+' '+b for a in list1 for b in list2 if a != b]
['hi moon', 'hi sun', 'hi flower', 'state moon', 'state sun', 'state hi', 'state flower', 'California moon', 'California sun', 'California hi', 'California flower', 'usa moon', 'usa sun', 'usa hi', 'usa flower']
这相当于较长的形式:
>>> L = []
>>> for a in list1:
... for b in list2:
... if a != b:
... L.append(a+' '+b)
...
>>> L
['hi moon', 'hi sun', 'hi flower', 'state moon', 'state sun', 'state hi', 'state flower', 'California moon', 'California sun', 'California hi', 'California flower', 'usa moon', 'usa sun', 'usa hi', 'usa flower']