【问题标题】:I need to append a list into another list (specific issue)我需要将一个列表附加到另一个列表中(具体问题)
【发布时间】:2019-09-06 02:27:00
【问题描述】:

这是我的代码:

files = open('clean.txt').readlines()
print files
finallist = []
for items in files:
  new = items.split()
  new.append(finallist)

由于文本文件太大,这里以“打印文件”为例:

files = ['chemistry leads outstanding another story \n', 'rhapsodic moments blow narrative prevent bohemian rhapsody']

我真的需要将由 '\n' 分隔的每一行拆分为单词并放入列表列表中,就像下面的格式一样:

outcome = [['chemistry','leads','outstanding', 'another', 'story'],['rhapsodic','moments','blow', 'narrative', 'prevent', 'bohemian', 'rhapsody']]

我已经尝试过类似于给出的第一个代码的方法,它返回一个空列表。请帮忙!提前致谢。

【问题讨论】:

  • finallist.append(new)?也许在发布之前至少进行校对会很好......
  • 嘿@Julien,对不起,这不是校对。我真的犯了那个错误。愚蠢的错误。非常感谢!我要关闭它。

标签: python python-2.7 list split append


【解决方案1】:

您的代码的最后一行似乎是倒退的。而不是

new.append(finallist)

应该是

finallist.append(new)

我把最后一行改成上面的版本,结果是一个包含2个子列表的列表(finallist)。这是似乎有效的代码:

files = open('clean.txt').readlines()
print files
finallist = []
for items in files:
  new = items.split()
  finallist.append(new)

【讨论】:

    【解决方案2】:

    使用列表推导来减少行数

    finallist = [i.split() for i in files]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-17
      • 2022-10-25
      • 2018-01-13
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      相关资源
      最近更新 更多