我有一份清单,大约有177071007项。 我正在尝试执行以下操作 a) 获取列表中唯一项的第一次和最后一次。 b) 发生次数。在
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)的顺序排列的。 我说的是让它快速的跑吗?或者还有别的办法吗?不幸的是,我没有numpy
扫描输入文件中的项时,将这些项放入
collections.defaultdict(list)
,其中键是项,值是出现索引的列表。读取文件并建立此数据结构需要线性时间,而获取项的第一次和最后一次出现索引需要恒定时间,而获取项的出现次数则需要恒定时间。在下面是它的工作原理
也许它值得改变使用的数据结构。我将使用一个dict,它使用pc作为键,使用occurrence作为值。在
尝试以下操作:
这是通过在读取}值只用于保存键所在的行。在
TSV
时创建一个字典,以pc
值为键,以出现列表为值。根据dict的性质,键必须是唯一的,因此我们避免使用set
,而{示例:
^{pr2}$将输出:
相关问题 更多 >
编程相关推荐