【发布时间】:2016-02-10 05:31:03
【问题描述】:
我正在对 CSV 文件进行一些计算。谁能帮我解释一下为什么方法 1 比方法 2 快 3 倍?我想让我的代码更加通用和可持续,所以我不想像方法 1 那样硬编码,但是一旦我切换到方法 2,性能就会急剧下降,我不知道为什么。
方法一:
for row in itertools.islice(csv_f, 0, period):
voltage_rail1 = float(row[rail1_index])
voltage_rail1_q.append(voltage_rail1)
current_rail1 = float(row[current_index])
current_rail1_q.append(current_rail1)
power_rail1_q.append(voltage_rail1*current_rail1)
voltage_rail2 = float(row[rail2_index])
voltage_rail2_q.append(voltage_rail2)
current_rail2 = float(row[current_index])
current_rail2_q.append(current_rail2)
power_rail2_q.append(voltage_rail2*current_rail2)
方法二:
rails_d = OrderedDict()
rails_d['rail1'] = 0
rails_d['rail2'] = 1
for row in itertools.islice(csv_f, 0, period):
for rail in rails_d:
voltage_d[rail] = float(row[voltage_column_index_d[rail]])
voltage_dq[rail].append(voltage_d[rail])
current_d[rail] = float(row[current_column_index_d[rail]])
current_dq[rail].append(current_d[rail])
power_dq[rail].append(voltage_d[rail]*current_d[rail])
【问题讨论】:
标签: python csv dictionary