返回返回最后一个项目
问题描述:
Dish = namedtuple('Dish', 'name price calories')
da = Dish("Mac N' Cheese", 8.00, 750)
db = Dish('Grilled Cheese', 6.50, 500)
dc = Dish('Hamburger', 9.50, 1000)
dd = Dish('Caeser Salad', 8.25, 650)
de = Dish('Fish Tacos', 11.25, 1150)
DL = [ da, db, dc, dd, de ]
我需要按一定比例,但我写的函数来改变DL所有项目的价格只返回去返回返回最后一个项目
def Dishlist_change_price(DL: list, percentage: float) -> list:
result = [ ]
x = percentage/100
for i in DL:
y = i.price + (i.price * x)
result = i._replace(price = y)
return result
什么是错在它的代码只返回最后一道菜?以此类推,直到你改变结果的循环每次迭代
def Dishlist_change_price(DL: list, percentage: float) -> list:
result = []
x = percentage/100
for i in DL:
y = i.price + (i.price * x)
result.append(i._replace(price=y))
return result
答
使用append()方法添加元素到列表中。你需要的是result.append(i._replace(price = y))
。
答
你必须result = i._replace(price = y)
是最近DL:
答
修改的最后一行到追加到数组
像result.append(i._replace(价格= Y)
答
result = i._replace(price = y)
重新绑定result
由_replace()
返回新namedtuple
对象。作为该发生一次列表中的每个项目,只有最后一个从您的函数返回。您应该使用list.append()
代替:
result.append(i._replace(price = y))
或更好,但一个列表理解:
def Dishlist_change_price(DL: list, percentage: float) -> list:
x = 1 + percentage/100.0
return [d._replace(price=(d.price*x)) for d in DL]
你可能不应该使用_replace()
;方法名称中的首字母下划线表示它用于课堂上的私人用途。 (有关带有下划线的标识符,请参阅PEP-8)。但是,由于_replace()
是documented,并且在两个版本的Python中均可用,所以它不可能会消失或被更改。然而,一个更安全的方法是显式实例化一个新Dish
列表理解这样的范围内:
def Dishlist_change_price(DL: list, percentage: float) -> list:
x = 1 + percentage/100.0
return [Dish(d.name, d.price*x, d.calories) for d in DL]
小侧面说明:定义'X = 1个+百分比/ 100'然后'Y = i.price * x'会简化代码并减少浮点错误。当然,浮点数据对于财务数据来说是一个糟糕的数据类型;切换到'decimal.Decimal'或至少改变为'y = round(i.price * x,2)'会让您获得全部美分而不是部分便士,并且随着您重复调整价格而出现增长错误。 – ShadowRanger