【问题标题】:Python: loop over a list of string and using split()Python:遍历字符串列表并使用 split()
【发布时间】:2014-04-14 00:13:32
【问题描述】:

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

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' object has no attribute 'split'

【问题讨论】:

  • 您发布的代码没有显示该错误。
  • @mogambo split 永远不会在 text 上调用,而是在 item 上调用。
  • 糟糕!你是对的……我的错。正在删除评论。

标签: python string list loops split


【解决方案1】:

不要在此处使用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)]]

【讨论】:

    【解决方案2】:

    基于@Aशwini चhaudhary 的回复,如果您有兴趣从字符串片段中删除尾随的,s 和\ns,您可以这样做

    [y.rstrip(',\n') for x in text for y in x.split(' ')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-03
      • 1970-01-01
      • 2021-04-02
      • 1970-01-01
      • 2014-09-19
      相关资源
      最近更新 更多