有2个列表(但可以有很多):
a = ['Sasha ','walked along ','the highway']
b = ['Masha ','ran on ','the road']
我需要显示所有选项:
Sasha沿着高速公路走了
萨莎沿着这条路走了
玛莎沿着高速公路走
玛莎沿着路走
萨莎在高速公路上跑了
萨莎在路上跑
玛莎在高速公路上跑
玛莎在路上跑
答案 0 :(得分:1)
将itertools.product
与str.join
一起使用:
from itertools import product
a = ['Sasha ','walked along ','the highway']
b = ['Masha ','ran on ','the road']
# option 1: list comprehension
res = [''.join(tup) for tup in product(*zip(a, b))]
# option 2: map
res = list(map(''.join, product(*zip(a, b))))
['Sasha walked along the highway',
'Sasha walked along the road',
'Sasha ran on the highway',
'Sasha ran on the road',
'Masha walked along the highway',
'Masha walked along the road',
'Masha ran on the highway',
'Masha ran on the road']
答案 1 :(得分:0)
由于要打印所有选项,因此可以尝试以下操作:
a = ['Sasha ','walked along ','the highway']
b = ['Masha ','ran on ','the road']
ab = [list(i) for i in zip(a,b)]
for i in ab[0]:
for j in ab[1]:
for k in ab[2]:
print(i,j,k)
输出:
Sasha walked along the highway
Sasha walked along the road
Sasha ran on the highway
Sasha ran on the road
Masha walked along the highway
Masha walked along the road
Masha ran on the highway
Masha ran on the road
答案 2 :(得分:0)
简单地说,没有itertools和zip:
def scr(*lists):
rslt=[""]
for idx in range(len(lists[0])): # all of the lists has the same length
r=[]
for s in rslt:
for l in lists:
r.append( s+l[idx] )
rslt=r
return rslt
print(scr(a,b))
答案 3 :(得分:0)
重命名您的版本。这是正确的解决方案:
a = ['Sasha ','Masha ']
b = ['walked along ','ran on ']
c = ['the highway','the road']
ab = [list(i) for i in (a,b,c)]
for x in ab[0]:
for y in ab[1]:
for z in ab[2]:
print(x + y + z)
Sasha walked along the highway
Sasha walked along the road
Sasha ran on the highway
Sasha ran on the road
Masha walked along the highway
Masha walked along the road
Masha ran on the highway
Masha ran on the road