2017-08-04 120 views
-5

的两个列表一个长字符串我想转走两个列表,并通过遍历每个列表中的每个字符串和连接两个用空格隔开他们创造一个长字符串:创建一个从字符串

listA = ["a","b"] 
listb = ["1","2","3"] 

new_string = “A1 A2 A3 B1,B2,B3”

+0

'''.join(map(''。join,itertools.product(listA,listb)))' –

回答

0

试试这个:

from itertools import product 

listA = ["a","b"] 
listb = ["1","2","3"] 
new_string = " ".join(a + b for a, b in product(listA, listb)) 
print(new_string) 
>>> a1 a2 a3 b1 b2 b3 
0

这是非常简单的
print(' '.join([ str(i)+str(j) for i in listA for j in listB]))

+0

@whackamadoodle您能否指出错误具体是什么。 –

+1

对不起,我误解了这个问题,我的工作不正常。我刚删除它 –

0
In [14]: ' '.join([' '.join(x + i for i in listb) for x in listA]) 
Out[14]: 'a1 a2 a3 b1 b2 b3' 
0

这里是一个非常简单的解决问题的方法,它通常是在学习循环的开始授课(至少对我来说是):

listA = ["a","b"] 
listb = ["1","2","3"] 
new_string = "" 

for i in listA: 
    for j in listb: 
     #adding a space at the end of the concatenation 
     new_string = new_string+i+j+" " 


print(new_string) 

在python 3中编码。