无法附加到列表中

时间:2015-07-05 08:09:53

标签: python

背景: 我的文本文件包含如下输入:

#1 GLN 15.A OE1
#1 ILE 16.A C
#1 ILE 16.A CA
#1 ILE 16.A CB
#1 ILE 16.A CD1

我将此文件转换为python中的字符串。我得到了我想要的输出(比如数字)。

代码的一部分在这里:

def extractnum(s):
   x = s.split('\n')
   x.pop() #To remove last line which is empty
   y = [ i.split() for i in x ]
   z = [ j[2] for j in y ] #z is the list that contains the residue and chain information
   n = [int(k.split('.')[0]) for k in z]
   a_chain_residues = ''
   ca_a_chain_residues = ''
   list_of_a_chain_residues = [ ]
   for i in list(set(z)): #list(set(z)) gives a list that removes all the duplicate items in z: it doesn't change z
      if i[-1] == 'A':
          a_chain_residues = a_chain_residues + i +','
          ca_a_chain_residues = ca_a_chain_residues + i + '.ca,'
          list_of_a_chain_residues = list_of_a_chain_residues.append(i)
      print list_of_a_chain_residues

终端中的错误读取

extractnum(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 17, in extractnum
AttributeError: 'NoneType' object has no attribute 'append'

为什么不能&#39;我&#39;添加到列表?有办法解决这个问题吗?

4 个答案:

答案 0 :(得分:3)

请注意:

>>>i = []
>>>print i.append(2)
None

此追加的返回值为None

所以,这样做的时候:

list_of_a_chain_residues = list_of_a_chain_residues.append(i)

您将list_of_a_chain_residues设置为None,因为追加不会返回值。 这样做:

list_of_a_chain_residues.append(i)

答案 1 :(得分:2)

append不会返回值;它直接修改列表。只需输入以下内容即可获得所需的效果:

list_of_a_chain_residues.append(i)

答案 2 :(得分:0)

问题是附加到列表会返回无,如果你这样做,你会得到答案

def extractnum(s):
    x = s.readlines()
    x.pop() #To remove last line which is empty
    y = [ i.split() for i in x ]
    z = [ j[2] for j in y ] #z is the list that contains the residue and chain information
    n = [int(k.split('.')[0]) for k in z]
    a_chain_residues = ''
    ca_a_chain_residues = ''
    list_of_a_chain_residues = [ ]
    for i in list(set(z)): #list(set(z)) gives a list that removes all the duplicate items in z: it doesn't change z
        if i[-1] == 'A':
            a_chain_residues = a_chain_residues + i +','
            ca_a_chain_residues = ca_a_chain_residues + i + '.ca,'
            list_of_a_chain_residues = list_of_a_chain_residues + list(i)
        print list_of_a_chain_residues

s = open("./file1.txt",'r')
extractnum(s)

答案 3 :(得分:0)

appendpython list方法的返回类型始终为None。 append()就地工作,即它然后修改原始列表。

list_of_a_chain_residues = list_of_a_chain_residues.append(i)

在上面一行中,毫无疑问,i中的值会被附加到列表list_of_a_chain_residues,但在下一刻,您将立即指定append的返回值到list_of_a_chain_residuesNone)。因此,即使列表被追加,将自己分配给append()的返回值会丢失所有进度并使其成为None。 因此,替换

list_of_a_chain_residues = list_of_a_chain_residues.append(i)

简单地通过

list_of_a_chain_residues.append(i)