2017-10-16 81 views
1

我有這個交錯兩個單詞並輸出新的交錯單詞作爲元組的代碼,但我也需要它是一個原始字符串。將一個列表格式化爲一個字符串Python

from itertools import zip_longest 
def interleave(word1,word2): 
    return ''.join(list(map(str, zip_longest(word1,word2,fillvalue='')))) 

如果輸入的話,貓和帽子,這個輸出

('h', 'c')('a', 'a')('t', 't'). 

但我需要它輸出

hcaatt 

我怎麼能去格式化這個名單成一個正常的字符串

+0

參見[製作一個平面列表出Python列表的列表(HTTPS:/ /stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python) – cowbert

回答

2

With itertools.chain.from_iterable() and zip()功能:

import itertools 

w1, w2 = 'cat', 'hat' 
result = ''.join(itertools.chain.from_iterable(zip(w2, w1))) 

print(result) 

輸出:

hcaatt 
0

你可以使用減少達到自己的目標:

word1, word2 = 'cat', 'hat' 
result = ''.join(reduce(lambda x, y: x+y, zip(word1, word2))) 
print(result) 
相關問題