【问题标题】:Files, lists, new-lines, and append()? [duplicate]文件、列表、换行符和 append()? [复制]
【发布时间】:2017-01-27 08:55:58
【问题描述】:

我有一个包含数据的文件:

ABC   acd   IGK  EFG

GHQ   ghq   acb  efg

IJK   ijk   gtt  ttg

我想拆分它的行并从每行中获取一些数据并将它们加入一个列表。像这样:

a = ['acd', 'ghq', 'ijk'] 

到目前为止,我已经完成了以下操作。

li = [] 

with open('file.txt') as fl:

    for f in fl:

        f = f.split()

        li = li.append(f[2])

但我收到以下错误:

Traceback (most recent call last):

  File "<stdin>", line 4, in <module>

AttributeError: 'NoneType' object has no attribute 'append'

有人可以帮我完成代码吗?

【问题讨论】:

  • 你有没有Google the error message
  • 诸如lists 和dicts 等可变对象的方法在原地更改它,例如list.append()dict.clear(),不返回被更改的对象。他们有效地返回None

标签: python list file split append


【解决方案1】:

你不需要做li = li.append(f[2])。你只需要li.append(f[2])

list.append 不返回任何内容,这就是您收到错误的原因。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-22
    • 2019-11-20
    • 1970-01-01
    • 2016-08-26
    • 1970-01-01
    • 2018-11-17
    • 2016-07-31
    相关资源
    最近更新 更多