【问题标题】:Printing elements out of list打印列表中的元素
【发布时间】:2010-03-23 16:20:40
【问题描述】:

我有一些检查要做,如果检查满足,我希望打印结果。下面是代码:

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 问题,所以我没有包含输入文件(基本上它们只是数字)。

谁能帮帮我?

干杯,

查瓦纳克

【问题讨论】:

    标签: python list printing


    【解决方案1】:

    要将字符串列表转换为列表项之间有空格的单个字符串,请使用' '.join(seq)。

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

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

    【讨论】:

    • 如果您不使用交互式提示,请在其前面添加“打印”。
    • str.join 将任何可迭代的字符串作为其参数。你传递的是一个list,而不是一个数组; “数组”指的是 Python 中一种不同的、不常用的类型。
    • 是的,我最近看太多Ruby了。
    【解决方案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]
    • 不要选择名称来包含它们所引用的对象的类型。可以通过其他方式找到此信息。

    例如,您发布的代码可以简化为类似于

    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 可以?),那么你可以考虑改进你的算法,可能使用集合或字典。

    【讨论】:

      猜你喜欢
      • 2011-10-11
      • 1970-01-01
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      相关资源
      最近更新 更多