2017-10-20 323 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']