从lis打印元素

2024-05-14 00:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个特定的检查要做,如果检查满足,我想打印结果。下面是代码:

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'],但是我希望得到351342(中间有一个空格)。因为这更多的是一个python问题,所以我没有包括输入文件(基本上它们只是数字)。

有人能帮我吗?

干杯

查瓦纳克


Tags: the代码infromimporttxtnewstring
2条回答

Mark Rushakoff似乎已经解决了您当前的问题,但是您的代码还可以做一些其他的改进。

  • 始终使用上下文管理器(with open(filename, mode) as f:)打开文件,而不是依赖于手动调用close
  • 不要经常把整个文件读入内存。循环覆盖some_file.readilines()可以直接替换为循环覆盖some_file

    • 例如,您可以使用map(string.strip, ligland_file)或更好的[line.strip() for line in ligland_file]
  • 不要选择名称来包含它们引用的对象的类型。这些信息可以通过其他方式找到。

对于exmaple,您发布的代码可以简化为

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是ac.txt中唯一计数c中的行长度。如果其中两个是固定的/小的,那么就有线性性能。如果两个可以任意增长(我想n和m可以?),然后可以考虑改进算法,可能使用集合或dict。

要将字符串列表转换为在列表项之间有空格的单个字符串,请使用^{}

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

您可以将' '替换为项目之间所需的任何字符串。

相关问题 更多 >