gpt4 book ai didi

python - 在 python 中循环操作的一行

转载 作者:太空宇宙 更新时间:2023-11-04 09:54:05 24 4
gpt4 key购买 nike

我对循环代码有优化问题:

我的代码是这样的:

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]

但我无法优化操作总数

感谢您的帮助。

最佳答案

我安排了几个变体供您比较:

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

关于python - 在 python 中循环操作的一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46616641/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com