以这段代码为例,你能解释为什么在列表中添加整数和时使用列表理解比使用普通的 for
循环花费更长的时间吗?
class Store:
def __init__(self, name):
self.name = name
self.items = []
def add_items(self, name, price):
self.items.append({'name':name, 'price': price})
def stock_price(self):
return sum([item['price'] for item in self.items])
def stock_price2(self):
total = 0
for item in self.items:
total += item.get('price')
return total
store = Store("Jay")
store.add_items("nike", 100)
store.add_items('puma', 200)
print(timeit.Timer(lambda: store.stock_price()).timeit(number=1000))
print(timeit.Timer(lambda: store.stock_price2()).timeit(number=1000))
stock_price 的结果:0.0007737720006844029
stock_price2 的结果:0.0006722800026182085
最佳答案
在第一个函数中,有一个额外的步骤。它首先创建一个列表,然后使用 sum
将所有列表相加。第二个函数简单地迭代它们并将其添加到总数中。
关于python - 为什么列表理解比在 for 循环中使用 += 需要更长的时间来执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51028091/