gpt4 book ai didi

python - 函数内的字典值和列表值

转载 作者:行者123 更新时间:2023-12-03 23:44:17 24 4
gpt4 key购买 nike

我有一本包含产品名称和价格的字典:

products = {'a': 2, 'b': 3, 'c': 4, 'd': 5, 'e': 6, 'f': 7, 'g': 8}
以及每个产品数量的列表:
amounts = [3, 0, 5, 1, 3, 2, 0]
我想得到一个显示该订单总价的输出。
不使用函数我似乎做对了:
products = {'a': 2, 'b': 3, 'c': 4, 'd': 5, 'e': 6, 'f': 7, 'g': 8}
amounts = [3, 0, 5, 1, 3, 2, 0]
res_list = []
order = []

for value in products.values():
res_list.append(value)

for i in range(0, len(res_list)):
order.append(amounts[i] * res_list[i])
total = sum(order)

print(res_list)
print(order) #this line and the one above are not really necessary
print(total)
输出:63
但是当我尝试在函数中使用此代码时,我遇到了一些问题。这是我尝试过的:
products = {'a': 2, 'b': 3, 'c': 4, 'd': 5, 'e': 6, 'f': 7, 'g': 8}
amounts = [3, 0, 5, 1, 3, 2, 0]
#order = []
def order(prod):
res_list = []
for value in prod.values():
res_list.append(value)
return res_list

prices = order(products)
print(prices)

def order1(prices):
order =[]
for i in range(0, len(prices)):
order.append(amounts[i] * prices[i])
total = sum(order)
return total

print(order1(prices))
没有按照预期的方式工作。
感谢您对我学习的所有帮助。

最佳答案

直接的问题是你的台词:

    total = sum(order)
return total
缩进太多,以至于它们在 for 内环形。在函数之外,错误并不重要,因为所发生的一切都是在每次迭代时重新计算总数,但最终值是使用的值。但是在函数内部,会发生的是 return在第一次迭代中。
减少缩进,使其在 for 之外循环将解决这个问题。
def order1(prices):
order =[]
for i in range(0, len(prices)):
order.append(amounts[i] * prices[i])
total = sum(order)
return total
但是,除此之外,您依赖于字典中的顺序,这仅适用于 Python 3.7 及更新版本。如果你想让代码在早期版本的 Python 上可靠地运行,你可以使用 OrderedDict .
from collections import OrderedDict

products = OrderedDict([('a', 2), ('b', 3), ('c', 4), ('d', 5),
('e', 6), ('f', 7), ('g', 8)])
顺便说一下,您的 order功能是不必要的。如果要转换 products.values() (字典值迭代器)到一个列表,只需使用:
prices = list(products.values())
此外,在 order1没有必要建立 order列出并总结它 - 你可以使用:
    total = 0
for i in range(0, len(prices)):
total += amounts[i] * prices[i]
现在这可能已经足够了,但是如果您想进一步改进,请查看如何 zip已使用,并考虑如何将它与您的循环一起使用 amountsprices .

关于python - 函数内的字典值和列表值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63810107/

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