我正在尝试使用 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”没有分开,我该如何避免这个问题?
请您参考如下方法:
研究列表理解,它们很棒。
这是你的答案:
[word for string in data for word in string.split(", ")]
