Concatenate strings in 2 different lists [duplicate]

余生颓废 提交于 2020-05-22 07:58:43

问题


I need to concatenate 2 different lists of strings in python.

for example:

list1 = ['A','B','C']
list2 = ['D', 'E']

I want to obtain

list3 = ['AD', 'AE', 'BD', 'BE', 'CD', 'CE']

I've tried:

list3 = zip(list1,list2)

And it returns

list3 = [('A','D'), ('B','E')]

I've also tried:

list(itertools.product(list1, list2))

But it returns

[('A','D'),('A','E'),...,('C','E')] and not ['AD', 'AE', 'BD', 'BE', 'CD', 'CE']

Any idea? THX


回答1:


This should help:

import itertools

list1 = ['A','B','C']
list2 = ['D', 'E']
list(map("".join, itertools.product(list1, list2)))
# ['AD', 'AE', 'BD', 'BE', 'CD', 'CE']

Also, can be solved with a list comprehension.

["".join(i) for i in itertools.product(list1, list2)]



回答2:


You could use itertools.product to get the Cartesian product or employ 2 loops

>>> list1 = ['A','B','C']
>>> list2 = ['D', 'E']
>>> import itertools
>>> list(itertools.product(list1, list2))
[('A', 'D'), ('A', 'E'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E')]
>>> [(i, j) for i in list1 for j in list2]
[('A', 'D'), ('A', 'E'), ('B', 'D'), ('B', 'E'), ('C', 'D'), ('C', 'E')]



回答3:


How about two for loops?

pseudocode below

for item in list1:
    for item2 in list2:
         item = item + item2


来源:https://stackoverflow.com/questions/36885876/concatenate-strings-in-2-different-lists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!