我有一個包含大約177071007項的列表。 我試圖執行以下操作 a)獲取列表中唯一項目的第一個和最後一個發生。 b)發生的次數。蟒蛇中的巨大列表的時間複雜度2.7
def parse_data(file, op_file_test):
ins = csv.reader(open(file, 'rb'), delimiter = '\t')
pc = list()
rd = list()
deltas = list()
reoccurance = list()
try:
for row in ins:
pc.append(int(row[0]))
rd.append(int(row[1]))
except:
print row
pass
unique_pc = set(pc)
unique_pc = list(unique_pc)
print "closing file"
#takes a long time from here!
for a in range(0, len(unique_pc)):
index_first_occurance = pc.index(unique_pc[a])
index_last_occurance = len(pc) - 1 - pc[::-1].index(unique_pc[a])
delta_rd = rd[index_last_occurance] - rd[index_first_occurance]
deltas.append(int(delta_rd))
reoccurance.append(pc.count(unique_pc[a]))
print unique_pc[a] , delta_rd, reoccurance[a]
print "printing to file"
map_file = open(op_file_test,'a')
for a in range(0, len(unique_pc)):
print >>map_file, "%d, %d, %d" % (unique_pc[a], deltas[a], reoccurance)
map_file.close()
然而,複雜度是按照O(n)的順序。 是否有可能讓for循環「跑得快」,我的意思是,你認爲屈服會讓它快嗎?或者還有其他方法嗎?不幸的是,我沒有numpy
如何繼續不同? :) – pistal
@pistal --' continue'移到循環的下一個迭代(不在其後面運行任何代碼),而'pass'將在下一次迭代之前運行任何代碼。一個很好的答案與示例[here。](http://stackoverflow.com/a/9484008/1401034) – Ewan