python中用于循环操作的一行
对于循环代码,我有优化的问题: 我的代码如下:python中用于循环操作的一行,python,for-loop,optimization,Python,For Loop,Optimization,对于循环代码,我有优化的问题: 我的代码如下: total = 0 result = [] for test in testing: total += test.amount result.append({'category': test.category, 'value': test.amount}) 我需要优化代码到一行。我正在尝试将代码更改为 total = 0 result = [ {'category': test.category, 'value': test.a
total = 0
result = []
for test in testing:
total += test.amount
result.append({'category': test.category, 'value': test.amount})
我需要优化代码到一行。我正在尝试将代码更改为
total = 0
result = [ {'category': test.category, 'value': test.amount} for test in testing]
但我无法优化整个操作
谢谢您的帮助。关于您的代码的一些有趣的观察结果:
总计
和构建结果
列表是独立的
本机python构造快速完成
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum(d['value'] for d in result)
编辑以显示总计是通过循环一个dict列表并对每个dict的值
键求和得到的
顺便说一下,这两行代码都是经过优化的python结构。关于代码的一些有趣的观察:
总计
和构建结果
列表是独立的
本机python构造快速完成
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum(d['value'] for d in result)
编辑以显示总计是通过循环一个dict列表并对每个dict的值
键求和得到的
顺便说一句,这两行代码都是经过优化的python结构。我为您比较了几个变体:
from functime import functime
class test_class:
def __init__(self, amt=10, cat='A'):
self.amount = amt
self.category = cat
def func_1(testing):
total = 0
result = []
for test in testing:
total += test.amount
result.append({'category': test.category, 'value': test.amount})
return
def func_2(testing):
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum([i['value'] for i in result])
return
def func_3(testing):
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum([test.amount for test in testing])
return
def func_4(testing):
result, totals = [], []
for test in testing:
totals.append(test.amount)
result.append({'category': test.category, 'value': test.amount})
total = sum(totals)
return
def func_5(testing):
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum(test.amount for test in testing)
return
为了节省空间,我将省略对函数和打印语句的调用:
--------------------
10 variables / 10000 iterations
--------------------
func_1: 0.0898552949414
func_2: 0.0572853889704
func_3: 0.0666673211647
func_4: 0.0676401432815
func_5: 0.0496420416234
--------------------
100 variables / 10000 iterations
--------------------
func_1: 0.371173584934
func_2: 0.310192364417
func_3: 0.330012053177
func_4: 0.53144825992
func_5: 0.377762000408
--------------------
1000 variables / 10000 iterations
--------------------
func_1: 3.60984478132
func_2: 3.05880308072
func_3: 3.29883265808
func_4: 4.98255212296
func_5: 3.36148284866
我为您选择了几个不同的时间进行比较:
from functime import functime
class test_class:
def __init__(self, amt=10, cat='A'):
self.amount = amt
self.category = cat
def func_1(testing):
total = 0
result = []
for test in testing:
total += test.amount
result.append({'category': test.category, 'value': test.amount})
return
def func_2(testing):
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum([i['value'] for i in result])
return
def func_3(testing):
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum([test.amount for test in testing])
return
def func_4(testing):
result, totals = [], []
for test in testing:
totals.append(test.amount)
result.append({'category': test.category, 'value': test.amount})
total = sum(totals)
return
def func_5(testing):
result = [{'category': test.category, 'value': test.amount} for test in testing]
total = sum(test.amount for test in testing)
return
为了节省空间,我将省略对函数和打印语句的调用:
--------------------
10 variables / 10000 iterations
--------------------
func_1: 0.0898552949414
func_2: 0.0572853889704
func_3: 0.0666673211647
func_4: 0.0676401432815
func_5: 0.0496420416234
--------------------
100 variables / 10000 iterations
--------------------
func_1: 0.371173584934
func_2: 0.310192364417
func_3: 0.330012053177
func_4: 0.53144825992
func_5: 0.377762000408
--------------------
1000 variables / 10000 iterations
--------------------
func_1: 3.60984478132
func_2: 3.05880308072
func_3: 3.29883265808
func_4: 4.98255212296
func_5: 3.36148284866
正如你所要求的那样,我知道如何在一条线上完成这一切。这肯定不是办法,但这里有几个选择:
def one_line():
return [(a[0][0], a[1]) for a in [ (t, [tuple(t.append(t.pop()+test.amount) or te for te in [{'category': test.category, 'value': test.amount}])[0] for test in testing ]) for t in [[0]] ] ][0]
def one_line_alternative():
return next(map(lambda a: (a[0].pop(),a[1]), [ (t, list(map(lambda test: next((t.append(t.pop()+test.amount)) or te for te in [{'category': test.category, 'value': test.amount}]), testing)) ) for t in [[0]] ]))
这里是一个与Evan Nowak最快答案的比较。我使用了10个变量,50000次迭代,以及Evan Nowak对10个变量的最快优化
One Line: 2.8529339203163353
One Line Alternative: 2.859311107199918
Evan Nowak's fastest optimization: 2.3440381323539983
所以,正如预期的那样,将所有内容放在一行上并不是一个好主意。正如您所要求的,我想出了如何将所有内容放在一行上。这肯定不是办法,但这里有几个选择:
def one_line():
return [(a[0][0], a[1]) for a in [ (t, [tuple(t.append(t.pop()+test.amount) or te for te in [{'category': test.category, 'value': test.amount}])[0] for test in testing ]) for t in [[0]] ] ][0]
def one_line_alternative():
return next(map(lambda a: (a[0].pop(),a[1]), [ (t, list(map(lambda test: next((t.append(t.pop()+test.amount)) or te for te in [{'category': test.category, 'value': test.amount}]), testing)) ) for t in [[0]] ]))
这里是一个与Evan Nowak最快答案的比较。我使用了10个变量,50000次迭代,以及Evan Nowak对10个变量的最快优化
One Line: 2.8529339203163353
One Line Alternative: 2.859311107199918
Evan Nowak's fastest optimization: 2.3440381323539983
因此,正如预期的那样,将所有内容放在一行不是一个好主意。你需要描述你的问题,而不仅仅是说你有问题。具体一点,告诉我们你有什么想法tried@shafeen我需要优化代码到一行。我试图将代码更改为total=0 result=[{'category':test.category,'value':test.amount}用于测试中的测试]但无法优化操作total您在优化什么?你尝试过什么?你说的“优化代码到一行”是什么意思?在什么意义上优化?一行并不意味着它将是最优的。你需要描述你的问题,而不仅仅是说你有问题。具体一点,告诉我们你有什么想法tried@shafeen我需要优化代码到一行。我试图将代码更改为total=0 result=[{'category':test.category,'value':test.amount}用于测试中的测试]但无法优化操作total您在优化什么?您尝试过什么?什么意思是“将代码优化为一行”,在什么意义上进行优化?一行并不意味着它将是最优的。将
sum(test.amount for uuuuuu结果)
更改为sum([test.amount for uuuuuuuuuuuu结果])
将加快函数的速度。您可以查看我的答案,查看计时结果。我现在明白了,我没有在我的答案中添加这些精确的比较,但在返回代码后,我的注释仍然是正确的(快了0.05秒)。+1检查您答案的完整性。我有点惊讶,我本以为在求和之前构建列表会带来一些开销。@XeroSmith我认为创建生成器并使用StopIteration异常停止它可能会有一些开销,如果不创建列表,所有这些都会发生。生成器对于减少使用的内存量非常有用,但看起来它们在速度方面效率不高。将sum(test.amount for uuu结果)
更改为sum([test.amount for uuuuuu结果])
将加快函数的速度。您可以查看我的答案,查看计时结果。我现在明白了,我没有在我的答案中添加这些精确的比较,但在返回代码后,我的注释仍然是正确的(快了0.05秒)。+1检查您答案的完整性。我有点惊讶,我本以为在求和之前构建列表会带来一些开销。@XeroSmith我认为创建生成器并使用StopIteration异常停止它可能会有一些开销,如果不创建列表,所有这些都会发生。生成器对于减少使用的内存量非常有用,但在速度方面似乎效率不高。有趣的是,您的示例测试让我尝试pip install functime not foundhey@Evan我刚刚更新了我的解决方案,它与其他解决方案相比表现如何?@XeroSmith将其更改为sum([d['value']对于结果中的d()
仍然可以提高速度,就像我在评论中提到的那样earlier@KomangSuryadanafunctime只是我为TimeIt制作的一个包装器,它对您的make示例测试很有兴趣,让我尝试pip安装functime not foundhey@Evan我刚刚更新了我的解决方案,它对其他人的表现如何?@XeroSmith将其更改为sum([d['value']表示结果中的d])
仍然可以提高速度,就像我在评论中提到的那样earlier@KomangSuryadanafunctime只是我为timeit做的一个包装