我有两个字符串列表,我想以元素方式连接它们以创建第三个列表
第三个列表应包含list_1
的所有元素,并为元素list_1
+ list_2
注意两个列表不一定具有相同的长度
示例:
base = ['url1.com/','url2.com/', 'url3.com/',...]
routes = ['route1', 'route2', ...]
urls = ['url1.com/' + 'url1.com/route1', 'url1.com/route2', 'url2.com/', 'url2.com/route1', 'url2.com/route2', ...]
我尝试使用zip
方法,但没有成功
urls = [b+r for b,r in zip(base,routes)]
答案 0 :(得分:4)
[x + y for x in list_1 for y in [""] + list_2]
产生输出:
['url1.com/',
'url1.com/route1',
'url1.com/route2',
'url2.com/',
'url2.com/route1',
'url2.com/route2',
'url3.com/',
'url3.com/route1',
'url3.com/route2']
顺便说一下,你要寻找的术语是笛卡尔积(略有修改),而不是元素串联,因为你可以选择每种可能的组合。
答案 1 :(得分:0)
您可以制作所有这些产品的产品,然后将它们加入新列表中:
import itertools
base = ['url1.com/','url2.com/', 'url3.com/']
routes = ['route1', 'route2']
products = [base,routes]
result = []
for element in itertools.product(*products):
result.append(element[0] + element[1])
print(result)
['url1.com/route1','url1.com/route2','url2.com/route1', 'url2.com/route2','url3.com/route1','url3.com/route2']
更多python方式:
print(list(element[0] + element[1] for element in itertools.product(*products)))