从列表中打印元素

1 投票
2 回答
8654 浏览
提问于 2025-04-15 20:45

我有一个检查要做,如果检查通过了,我想把结果打印出来。下面是代码:

import string
import codecs
import sys
y=sys.argv[1]

list_1=[]
f=1.0
x=0.05
write_in = open ("new_file.txt", "w")
write_in_1 = open ("new_file_1.txt", "w")
ligand_file=open( y, "r" ) #Open the receptor.txt file
ligand_lines=ligand_file.readlines() # Read all the lines into the array
ligand_lines=map( string.strip, ligand_lines ) #Remove the newline character from all     the pdb file names
ligand_file.close()

ligand_file=open( "unique_count_c_from_ac.txt", "r" ) #Open the receptor.txt file
ligand_lines_1=ligand_file.readlines() # Read all the lines into the array
ligand_lines_1=map( string.strip, ligand_lines_1 ) #Remove the newline character from all the pdb file names
ligand_file.close()
s=[]
for i in ligand_lines:
   for j in ligand_lines_1:
      j = j.split()
      if i == j[1]:
     print j

上面的代码运行得很好,但当我打印 j 的时候,它显示的是 ['351', '342'],我其实希望看到的是 351 342(中间有一个空格)。因为这更像是个 Python 的问题,所以我没有包含输入文件(基本上它们就是一些数字)。

有人能帮我吗?

谢谢,

Chavanak

2 个回答

2

Mark Rushakoff 似乎解决了你眼前的问题,但你的代码还有一些可以改进的地方。

  • 打开文件时,最好使用上下文管理器(with open(filename, mode) as f:),而不是手动调用 close 来关闭文件。
  • 不要经常把整个文件读入内存。你可以直接循环遍历 some_file,而不是用 some_file.readlines()

    • 比如,你可以用 map(string.strip, ligland_file),或者更好的是 [line.strip() for line in ligland_file]
  • 给对象命名时,不要把对象的类型放在名字里。这些信息可以通过其他方式获取。

例如,你发的代码可以简化成类似下面的样子:

import sys
from contextlib import nested

some_real_name = sys.argv[1]
other_file = "unique_count_c_from_ac.txt"

with nested(open(some_real_name, "r"), open(other_file, "r")) as ligand_1, ligand_2:
    for line_1 in ligand_1:
        # Take care of the trailing newline
        line_1 = line_1.strip()

        for line_2 in ligand_2:
            line_2 = line2.strip()

            numbers = line2.split()

            if line_1 == numbers[1]:
                # If the second number from this line matches the number that is 
                # in the user's file, print all the numbers from this line
                print ' '.join(numbers)

这样更可靠,我觉得也更容易阅读。

需要注意的是,这段代码的算法性能并不是很好,因为有嵌套循环。根据你的需求,这可能有改进的空间,但我不知道你具体需要提取什么数据,所以不能确定。

目前我和你的代码运行时间是 O(nmq),其中 n 是一个文件的行数,m 是另一个文件的行数,q 是 unique_count_c_from_ac.txt 中行的长度。如果其中两个是固定的或比较小,那么性能是线性的。如果两个可以无限增长(我想 n 和 m 是可以的?),那么你可能需要考虑改进你的算法,可能可以使用集合或字典。

9

如果你想把一个字符串列表变成一个单一的字符串,并且在每个字符串之间加上空格,可以使用 ' '.join(seq) 这个方法。

>>> ' '.join(['1','2','3'])
'1 2 3'

你可以把 ' ' 替换成你想要的任何字符串,这样在每个项目之间就会显示你指定的内容。

撰写回答