[英]How to transform nested strings in array to separated words?
I'm trying to do a simple array & string transformation with Python yet I'm stuck. 我正在尝试使用Python做一个简单的数组和字符串转换,但是我被困了。 I have this array :
我有这个数组:
data = ['one, two, three', 'apple, pineapple', 'frog, rabbit, dog, cat, horse']
And I would like to arrive to this result : 我想得出这个结果:
new_data = ['one', 'two', 'three', 'apple', 'pineapple', 'frog', 'rabbit', 'dog', 'cat', 'horse']
This is what I'm doing but whenever I use 这就是我在做的,但是每当我使用时
data_to_string = ''.join(data)
new_data = re.findall(r"[\w']+", data_to_string)
it gives me this : 它给了我这个:
['one', 'two', 'threeapple', 'pineapplefrog', 'rabbit', 'dog', 'cat', 'horse']
As you can see "threeapple" and "pineapplefrog" aren't separated, how can I avoid this issue ? 如您所见,“ threeapple”和“ pineapplefrog”没有分开,如何避免这个问题?
How about some simple list comprehension and string methods? 一些简单的列表理解和字符串方法怎么样?
re
is overkill for this. 对于这个来说,
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']
Look into list comprehensions, they're great. 调查列表理解,它们很棒。
Here's your answer: 这是您的答案:
[word for string in data for word in string.split(", ")]
use join and split 使用连接和拆分
','.join(data).split(',')
results in 结果是
['one',
' two',
' three',
'apple',
' pineapple',
'frog',
' rabbit',
' dog',
' cat',
' horse']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.