问题
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