2017-03-07 79 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'] 
+0

其他的答案是正確的爲好。但是如果你有像數據* 10那樣的大型數組,那麼你就可以獲得性能優勢的join和split命令。 %timeit','。join(data * 10).split(',')100000循環,最好是3:每循環10.3μs%timeit [數據中字符串的字符串(*)* 10字符串中的字符串。 (',')] 10000個循環,最好是3:每循環42.4μs。不是什麼大不了的事,而是想分享。 – plasmon360

2

分裂

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

結果怎麼樣了一些簡單的列表理解和字符串的方法呢? 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'] 
相關問題