简体   繁体   English

Append 到 for 循环和 if 语句中的空列表

[英]Append to an empty list within a for loop and an if statement

The program should read the data in the PDB file named 1A36.pdb, and for each distinct atom in it, store a record for that atom in an list of atom records.程序应该读取名为 1A36.pdb 的 PDB 文件中的数据,并且对于其中的每个不同原子,将该原子的记录存储在原子记录列表中。

I am trying to append 'line' into empty list 'atom_records' within the for loop.我正在尝试将 append 'line' 放入 for 循环中的空列表 'atom_records' 中。 When I print 'atom_records' I get duplicated records in scattered pattern, not sure why that is happening.当我打印“atom_records”时,我得到分散模式的重复记录,不知道为什么会这样。

Expected Output when printing 'atom_records':打印“atom_records”时预期的 Output:

https://i.stack.imgur.com/sfQsU.png https://i.stack.imgur.com/sfQsU.png

My code: Ignore the commented parts, that is part of the for loop to print count of atom records.我的代码:忽略注释部分,这是用于打印原子记录计数的 for 循环的一部分。


import sys


def atom_info(count):
    file = open(sys.argv[1], "r")
    contents = file.read()
    lines = contents.splitlines()
    atom_records = []
    for line in lines:
        if line.startswith('ATOM'):
            count += 1
            atom_records.append(line)
            print(atom_records)
    return count

#count = 0
#frequency = atom_info(count)
#print("Welcome to the pdb program. \nTo begin, try typing 'help' for #the list of valid commands.")
#print(frequency, "atoms recorded.")

here my answer:这是我的回答:

import sys


def atom_info(count):
    # file = open(sys.argv[1], "r")
    file = open('1a36.pdb' ,"r")
    contents = file.read()
    lines = contents.splitlines()
    atom_records = []
    for line in lines:
        if line.startswith('ATOM'):
            count += 1
            atom_records.append(line)
            # print(atom_records)     #delete here as suggested
            print(line)
            
    for i in atom_records:
        print(i)    #prints like : ATOM   5230  OXT PHE A 765      35.802  38.654  28.765  1.00 36.28           O  
        
    # print(atom_records) # prints like : 'ATOM   5229  CZ  PHE A 765      32.510  34.679  27.197  1.00 30.57           C  ', 
    return count

print('N# atoms : ',atom_info(0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM