84669 人学习
152542 人学习
20005 人学习
5487 人学习
7821 人学习
359900 人学习
3350 人学习
180660 人学习
48569 人学习
18603 人学习
40936 人学习
1549 人学习
1183 人学习
32909 人学习
认证高级PHP讲师
改了一下你的代碼, 這樣應該比較簡潔:
(根據 @依云 的建議又改了一下)
import os import sys def getinfo(filename) : info = {} with open(filename, 'r') as f: for line in f: ID, name = line.strip().split() info[ID] = name return info def matchname(info, input_file, output_file) : with open(input_file, 'r') as reader, open(output_file, 'w') as writer: for line in reader: n1, n2, content = line.strip().split() for ID, name in info.items(): if name in content: print(n1, n2, name, ID, sep='\t', file=writer) if __name__ == '__main__': info_filename = 'aa.txt' content_filename = 'bb.txt' result_filename = 'final_output2.txt' info = getinfo(info_filename) matchname(info, content_filename, result_filename) print('done')
(稍後回來補說明...)
我回答過的問題: Python-QA
in 当然比 find 快,因为前者比后者少了次属性查找、函数调用,多了次比较操作:
in
find
>>> def t(): ... return "abctestdef".find("testx") ... >>> import dis >>> dis.dis(t) 2 0 LOAD_CONST 1 ('abctestdef') 3 LOAD_ATTR 0 (find) 6 LOAD_CONST 2 ('testx') 9 CALL_FUNCTION 1 (1 positional, 0 keyword pair) 12 RETURN_VALUE >>> def t(): ... return "test" in "abctestdef" ... >>> dis.dis(t) 2 0 LOAD_CONST 1 ('test') 3 LOAD_CONST 2 ('abctestdef') 6 COMPARE_OP 6 (in) 9 RETURN_VALUE
想要更快,可以考虑使用 Rust :-)
另外你的代码写得不太好。文件操作建议使用 with 而不是手动关闭。
set的in时间复杂度是O(1)list的in时间复杂度是O(n)
你可以在组装的时候尝试使用集合
改了一下你的代碼, 這樣應該比較簡潔:
(根據 @依云 的建議又改了一下)
(稍後回來補說明...)
我回答過的問題: Python-QA
in
当然比find
快,因为前者比后者少了次属性查找、函数调用,多了次比较操作:想要更快,可以考虑使用 Rust :-)
另外你的代码写得不太好。文件操作建议使用 with 而不是手动关闭。
set的in时间复杂度是O(1)
list的in时间复杂度是O(n)
你可以在组装的时候尝试使用集合