<p>Mark Rushakoff似乎已经解决了您当前的问题,但是您的代码还可以做一些其他的改进。</p>
<ul>
<li>始终使用上下文管理器(<code>with open(filename, mode) as f:</code>)打开文件,而不是依赖于手动调用<code>close</code>。</li>
<li><p>不要经常把整个文件读入内存。循环覆盖<code>some_file.readilines()</code>可以直接替换为循环覆盖<code>some_file</code>。</p>
<ul>
<li>例如,您可以使用<code>map(string.strip, ligland_file)</code>或更好的<code>[line.strip() for line in ligland_file]</code></li>
</ul></li>
<li><p>不要选择名称来包含它们引用的对象的类型。这些信息可以通过其他方式找到。</p></li>
</ul>
<p>对于exmaple,您发布的代码可以简化为</p>
<pre><code>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)
</code></pre>
<p>这是更可靠的,我相信更容易阅读。</p>
<p>注意,由于这些嵌套循环,这种方法的算法性能远不理想。根据您的需要,这可能会得到改进,但因为我不知道您到底需要提取哪些数据来告诉您是否可以。</p>
<p>当前在我的代码和您的代码中所用的时间是O(n<em>m</em>q),其中n是一个文件中的行数,m是另一个文件中的行数,q是ac.txt中唯一计数c中的行长度。如果其中两个是固定的/小的,那么就有线性性能。如果两个可以任意增长(我想n和m可以?),然后可以考虑改进算法,可能使用集合或dict。</p>