2017-03-07 1 views
1

私は単純な配列をしようとしています& Pythonでの文字列変換はまだ止まっています。配列内のネストされた文字列を分割された単語に変換する方法はありますか?

data = ['one, two, three', 'apple, pineapple', 'frog, rabbit, dog, cat, horse'] 

そして、私はこの結果に到着したい:私はこの配列を持っている

new_data = ['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse'] 

これは私がやっているが、私は

data_to_string = ''.join(data) 
new_data = re.findall(r"[\w']+", data_to_string) 
を使用するたびものです

それは私にこれを与える:

['one', 'two', 'threeapple', 'pineapplefrog', 'rabbit', 'dog', 'cat', 'horse'] 

"threeapple"と "pineapplefrog"が分かれていないことがわかりますが、どうすればこの問題を回避できますか?

答えて

2

リスト内包表記に目を通してください。ここで

は、あなたの答えです:

[word for string in data for word in string.split(", ")] 
+1

次にリスト内包表記をチェックします:) – Lindow

1

使用が参加して、どのようにいくつかの単純なリストについて理解し、文字列のメソッド

['one', 
' two', 
' three', 
'apple', 
' pineapple', 
'frog', 
' rabbit', 
' dog', 
' cat', 
' horse'] 

','.join(data).split(',') 

結果

+0

他の回答にも正しいです。しかし、データ* 10のような大規模な配列を持っている場合は、パフォーマンスの向上に役立ちます。ループ(100,000ループ、3:10.3μs/ループ)timeit [word.strip()(データ内の文字列)* 10(string.split内の単語) ( '、')]ループ10000個、ループ3個あたり最高42.4μs。大したことではなく、分かち合うことを考えました。 – plasmon360

2

を分割しましたか?これに対してはreが過剰です。

>>> data = ['one, two, three', 'apple, pineapple', 'frog, rabbit, dog, cat, horse'] 
>>> [word.strip() for string in data for word in string.split(',')] 
['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse'] 
関連する問題