性能 - python 的in 和 find 执行效率问题
PHP中文网
PHP中文网 2017-04-18 09:22:21
0
3
676
PHP中文网
PHP中文网

认证高级PHP讲师

全部回覆(3)
小葫芦

改了一下你的程式碼, 這樣應該比較簡潔:

(根據 @依雲 的建議又改了一下)

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 快,因為前者比後者少了次屬性查找、函數調用,多了次比較操作:

>>> 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 而不是手動關閉。

PHPzhong

set的in時間複雜度是O(1)
list的in時間複雜度是O(n)

你可以在組裝的時候嘗試使用集合

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!