2017-08-04 126 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中編碼。