Python:遍历字符串列表并使用 split()

use*_*910 2 python string split loops list

我正在尝试拆分列表的元素:

text = ['James Fennimore Cooper\n', 'Peter, Paul, and Mary\n',
        'James Gosling\n']

newlist = ['James', 'Fennimore', 'Cooper\n', 'Peter', 'Paul,', 'and', 'Mary\n',
        'James', 'Gosling\n']
Run Code Online (Sandbox Code Playgroud)

到目前为止我的代码是:

newlist = []

for item in text:
    newlist.extend(item.split())

return newlist
Run Code Online (Sandbox Code Playgroud)

我得到错误:

builtins.AttributeError: 'list' object has no attribute 'split'

Ash*_*ary 5

不要split()在此处使用,因为它还会删除尾随'\n',请使用split(' ').

>>> text = ['James Fennimore Cooper\n', 'Peter, Paul, and Mary\n',
...         'James Gosling\n']
>>> [y for x in text for y in x.split(' ')]
['James', 'Fennimore', 'Cooper\n', 'Peter,', 'Paul,', 'and', 'Mary\n', 'James', 'Gosling\n']
Run Code Online (Sandbox Code Playgroud)

如果空格数不一致,则可能必须使用正则表达式:

import re
[y for x in text for y in re.split(r' +', x)]]
Run Code Online (Sandbox Code Playgroud)