gpt4 book ai didi

python - 提取字典字段以用作函数名称

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

我正在尝试通过引用字典使用 for 循环创建函数。

我的两次不同的尝试都没有成功:

dictionary = {1:'Apples', 2:'Pears', 3:'Carrots'}

for i in range(1, 4, 1):
name = dictionary[i]
def name(price, quantity):
total = price*quantity
return total

print(Apples(3, 2))

此方法不成功,因为“名称”成为正在定义的函数名称。 (名称错误)

for i in range(1, 4, 1):
def dictionary[i](price, quantity):
total = price*quantity
return total

这种方法不成功,因为在定义函数时有方括号被认为是语法错误。

有没有办法可以提取字典中字段的名称使其成为一个函数?

最佳答案

你可以做到

for i in range(1, 4, 1):
name = dictionary[i]
def _fn(price, quantity):
total = price*quantity
return total
globals()[name] = _fn

但很少需要这样做。

一个更明智的方法(如@martineau 所描述的)是将函数直接放在字典中:

def Apples(price, quantity):
total = price * quantity
return total

def Pears(...): ...
def Carrots(...): ...

dictionary = {1: Apples, 2: Pears, 3: Carrots}

你会这样调用函数:

dictionary[1](price=2.50, quantity=4)

如果您将 dictionary 重命名为 total ,它会非常可读:

product_id = 1
total_price = total[product_id](price=2.50, quantity=4)

如果所有函数都相同,那就更简单了:

def totalfn(price, quantity):
total = price * quantity
return total

total = {1: totalfn, 2: totalfn, 3: totalfn}

如果您有很多产品,甚至更短:

total = {productid: totalfn for productid in (1,2,3)}

关于python - 提取字典字段以用作函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54793901/

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