Concatenating Strings: “Multiplication” of two list of strings

若如初见. 提交于 2020-06-12 15:27:25

问题


For list of strings, define the multiplication operation in as concatenating here:

l1 = ['aa', 'bb', 'cc']
l2 = ['11', '22']
l3 = l1 op l2

Expected output:

l3 = ['aa11', 'aa22', 'bb11', 'bb22', 'cc11', 'cc22']

Simply we can use

for l in l1:
    for ll in l2:
        l3.append(l+ll)

But I'd be grateful to hear a pythonic solution.


回答1:


from itertools import product

l1 = ['aa', 'bb', 'cc']
l2 = ['11', '22']

l3 = [x+y for (x,y) in product(l1,l2)]

print(l3)

But it's effectively the same thing as what you're doing (provided you fix the typo :P)




回答2:


l3 = [a+b for a in l1 for b in l2]


来源:https://stackoverflow.com/questions/50689672/concatenating-strings-multiplication-of-two-list-of-strings

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