2017-10-20 324 views
0

我有一個字符串列表列表,我想將其轉換爲字符串列表,在每個列表項目之間添加一個空格。例如。將字符串列表轉換爲字符串列表

original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']] 

desired_output = ['the cat in the hat', 'fat cat sat on the mat'] 

我知道我可以用這個做到這一點:

desired_output 
for each in original_list: 
    desired_output.append(' '.join(each)) 

,但因爲我有大量數據的工作我的理想尋找一種更有效的方式來做到這一點。

+0

它應該是'''.join(each)'而不是'''.join(each)'代碼 –

+2

@KaushikNP Cheers - 這是一個錯字。 – jdoe

回答

4

使用str.join一個完整的空間' '

original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']] 
final_list = [' '.join(i) for i in original_list] 

輸出:

['the cat in the hat', 'fat cat sat on the mat'] 
+1

嗯,這是如何優化? OP已經這樣做了,只是不使用'list comprehension'。 –

+0

@KaushikNP'str.join'比字符串連接快得多,因爲字符串是不可變的,因此不能在適當位置進行更改。 – Ajax1234

+0

但這不是用戶所做的。 OP也使用了'join'。但是,有一件事我忽略了。用戶使用'append'和'list comprehension'在這裏有一點優勢。所以解決。 +1 –

1

另一個Python的,簡單的方法,在Python 3,可以使用map,說,另一個SO討論,它應該是更快,它會這樣:

original_list = [['the', 'cat', 'in', 'the', 'hat'], ['fat', 'cat', 'sat', 'on', 'the', 'mat']] 

#    (------where magic happens--------) 
desired_list = list(map(' '.join, original_list)) 

#print 
#output ['the cat in the hat', 'fat cat sat on the mat']