【发布时间】:2018-06-23 23:04:39
【问题描述】:
我有 2 个 for 循环,主要用于处理大量数据。我想对此进行优化并尽可能提高速度。
source = [['row1', 'row2', 'row3'],['Product', 'Cost', 'Quantity'],['Test17', '3216', '17'], ['Test18' , '3217' , '18' ], ['Test19', '3218', '19' ], ['Test20', '3219', '20']]
创建一个生成器对象
it = iter(source)
variables = ['row2', 'row3']
variables_indices = [1, 2]
getkey = rowgetter(*key_indices)
for row in it:
k = getkey(row)
for v, i in zip(variables, variables_indices):
try:
o = list(k) # populate with key values initially
o.append(v) # add variable
o.append(row[i]) # add value
yield tuple(o)
except IndexError:
pass
def rowgetter(*indices):
if len(indices) == 0:
#print("STEP 7")
return lambda row: tuple()
elif len(indices) == 1:
#print("STEP 7")
# if only one index, we cannot use itemgetter, because we want a
# singleton sequence to be returned, but itemgetter with a single
# argument returns the value itself, so let's define a function
index = indices[0]
return lambda row: (row[index],)
else:
return operator.itemgetter(*indices)
这将返回一个元组,但对于 100,000 行(源在示例中有 5 行)平均 100 秒要花费很多时间。任何人都可以帮助减少这个时间。
注意:我还尝试了内联循环和列表理解,但每次迭代都不会返回
【问题讨论】:
-
请将
source修复为真正有效的python。getkey还有什么作用?你为什么使用iter,i来自哪里?我们真的需要一个完整的工作示例! -
@match 我现在用完整的例子编辑了我的问题
-
还不清楚
i是什么? -
是内部的fr循环索引
标签: python python-3.x for-loop nested-loops