【问题标题】:Splitting words in a list拆分列表中的单词
【发布时间】:2020-02-19 08:59:29
【问题描述】:

如何将列表拆分为单独的单词。我知道您可以使用split 拆分字符串,但我需要拆分一个列表。

这是我的代码:

text = ['a,b', 'c,d']
text = text.replace(',', ' ')
for i in text:
  print(text.split())

当我运行它时,会弹出一个错误,当我尝试将列表转换为字符串时,会出现 \n' 等随机附加信息[] 不应该在那里。

预期结果:我希望结果是一个包含 ['a', 'b', 'c', 'd'] 的列表,当我打印时会得出这个结果。

错误出现在第二行并说:

AttributeError: 'list' 对象没有属性 'replace'

【问题讨论】:

标签: python split


【解决方案1】:

您可以轻松做到这一点,但首先您应该阅读split 函数的确切作用。

newList = []
for i in text:
    words = i.split(',')
    newList.extend(words)
print(newList)

这里有一些有用的信息,Python list extendIterating over a list

另外,对于lists,没有称为replace的方法,该方法适用于Strings。

【讨论】:

    【解决方案2】:
    your_list = [ x for sublist in text for x in sublist.split(',') ]
    

    【讨论】:

      【解决方案3】:

      列表没有replace 函数。我猜你想要的是用逗号分割:

      text = ['a,b', 'c,d']
      result = []
      for i in text:
        result.extend(i.split(','))
      

      请注意,我所做的第二个更改是打印 i - 与整个 text 相比,它是迭代的东西。此外,我在结果上调用 extend 以生成单个列表。

      【讨论】:

        【解决方案4】:

        另一种方法:

        text = ['a,b', 'c,d']
        text = ','.join(text)
        text = text.split(',')
        print(text)
        # ['a', 'b', 'c', 'd']
        

        【讨论】:

          【解决方案5】:

          您可以执行以下操作:

          text = ['a,b', 'c,d']
          text_str = "".join(text).replace(",", "")
          arr = [c for c in text_str]
          

          它有点冗长,但这些是步骤

          【讨论】:

            【解决方案6】:

            也许是这个?

            >>> from itertools import chain
            >>> text = ['a,b', 'c,d']
            >>> list(chain(*[item.split(',') for item in text]))
            ['a', 'b', 'c', 'd']
            

            【讨论】:

              猜你喜欢
              • 2019-03-20
              • 2017-08-16
              • 1970-01-01
              • 2018-03-13
              • 2018-04-06
              • 2019-07-24
              • 1970-01-01
              • 2013-04-20
              • 1970-01-01
              相关资源
              最近更新 更多