[英]Improving the speed of a python script
我有一個包含字符串列表的輸入文件。
我從第二行開始迭代每四行。
從這些行中的每一行開始,我從第一個和最后6個字符創建一個新字符串,並且僅當新字符串是唯一的時才將其放在輸出文件中。
我寫的代碼可以實現這一點,但是我正在使用非常大的深度排序文件,並且已經運行了一天並且沒有取得多大進展。 所以我正在尋找任何建議,如果可能的話,這樣做會更快。 謝謝。
def method():
target = open(output_file, 'w')
with open(input_file, 'r') as f:
lineCharsList = []
for line in f:
#Make string from first and last 6 characters of a line
lineChars = line[0:6]+line[145:151]
if not (lineChars in lineCharsList):
lineCharsList.append(lineChars)
target.write(lineChars + '\n') #If string is unique, write to output file
for skip in range(3): #Used to step through four lines at a time
try:
check = line #Check for additional lines in file
next(f)
except StopIteration:
break
target.close()
嘗試將lineCharsList
定義為set
而不是列表:
lineCharsList = set()
...
lineCharsList.add(lineChars)
這將提高性能in
運營商。 此外,如果內存根本不是問題,您可能希望在列表中累積所有輸出並在結尾處全部寫入,而不是執行多個write()
操作。
您可以使用https://docs.python.org/2/library/itertools.html#itertools.islice :
import itertools
def method():
with open(input_file, 'r') as inf, open(output_file, 'w') as ouf:
seen = set()
for line in itertools.islice(inf, None, None, 4):
s = line[:6]+line[-6:]
if s not in seen:
seen.add(s)
ouf.write("{}\n".format(s))
嘗試更換
lineChars = line[0:6]+line[145:151]
同
lineChars = ''.join([line[0:6], line[145:151]])
因為它可以更有效,取決於具體情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.