2017-03-07 46 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'] 
相关问题