2017-10-20 11 views
0

私は各リストアイテム間にスペースを追加する文字列のリストに変換したい文字列のリストを持っています。例えば。stringのリストのリストを効率的に文字列のリストに変換する

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 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'] 
関連する問題