【问题标题】:How to turn a string into a list of list?如何将字符串转换为列表列表?
【发布时间】:2020-03-23 02:24:45
【问题描述】:

我想把一个字符串用\n转成list的列表,然后用空格分割子列表中的字符串。

例子:-

('We are champion\n We won the game\n')

想要的结果:-

[['We', 'are', 'champion'], ['We', 'won', 'the', 'game']]

我不知何故对函数 split 感到困惑,并发现我不能在子列表中使用 split。

【问题讨论】:

  • 欢迎来到 Stack Overflow。请阅读stackoverflow.com/help/how-to-ask,了解如何提出一个好的问题,从而得到好的答案。在此期间,您能否更新您的问题并展示您迄今为止所做的尝试?

标签: python-3.x string split


【解决方案1】:

您可以使用splitlines 按新行分割字符串。然后将其循环到split 成单词并附加到结果的array

提示:在进行拆分之前,您可以使用strip 修剪字符串的空白。

txt = "We are champion\n We won the game\n"

xs = txt.strip().splitlines()

result = [];

for x in xs:
  result.append(x.split())

print(result)

【讨论】:

  • 感谢您告诉我分割线功能。但是这个结果将在列表中包含空子列表的地方将 \n 存在。你知道如何摆脱它吗?
  • 我已经更新了答案,添加了条带功能以删除空白空间。
【解决方案2】:

这应该适合你:

text = 'We are champion\n We won the game\n'

arr = []

for sentence in text.split('\n'):
    sentence = sentence.strip()

    if sentence:
        arr.append(sentence.split(' '))

print(arr)

【讨论】:

  • 感谢您的回答。实现代码后,我仍然得到像 [''] 这样的子列表。你知道如何摆脱它吗?谢谢:)
  • 感谢您的帮助。那么 if 语句帮助我们摆脱空列表对吧?
  • @Alex 是的!在 Python 中,空字符串被视为 False。本质上,我们是说如果单词列表为空,请不要将其添加到 arr 变量中。
猜你喜欢
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-17
相关资源
最近更新 更多