gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:03:42 24 4
gpt4 key购买 nike

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

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']

到目前为止我的代码是:

newlist = []

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

return newlist

我得到了错误:

builtins.AttributeError: 'list' 对象没有属性 'split'

最佳答案

不要在这里使用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']

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

import re
[y for x in text for y in re.split(r' +', x)]]

关于Python:遍历字符串列表并使用 split(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22307844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com