我对这个函数的目标是输出订单的总成本。
我有一个函数,它给出一个类似{'2': '150.99', '3': '99.50', '15': '5.07'}
的字典,其中第一个值是一个ID号,第二个值是具有该ID号的商品的价格。所以第三件商品的价格是99美元/欧元/英镑/无论我的单位是什么,50美分/子单位。
另一个函数为我提供了一个商品ID列表,可以像这样查找[2, 2, 3]
,其中任何商品ID都可以多次出现,以表明我正在购买该商品中的多个。因此,在这个例子中,我将以每件150.99英镑的价格购买2件商品2,以99.50%的价格购买商品3的1件。
我想定义一个函数,让我向它传递商品ID的字典:价格和要查找的商品ID列表,它将输出列表中所有商品的总成本。因此,对于上面的示例,它应该输出值401.48
,因为(2*150.99)+99.50=401.48
。
作为一个测试,我尝试过
test = DictionaryVariable.get('2')
print test
这将打印预期值(因此在本例中,该值将为150.99)。
但是,我尝试定义一个函数,比如
def FindPrice(dictionary, idlist):
price = 0.00
for id in idlist:
price + float(dictionary.get(id))
return price
然后这样叫它:
Prices = FindPrice(DictionaryVariable, IDListVariable)
print Prices
没有工作- dictionary.get(id)
部分似乎返回None
(我已经通过将其设置为字符串而不是浮点型进行了测试),因此它抛出一个错误,指出"TypeError: float()参数必须是字符串或数字“。我怀疑我需要使用其他方法来填充列表中的条目in,但我不知道该方法是什么。我不确定为什么dictionary.get(id)
返回None
,但是DictionaryVariable.get('2')
给出了我所期望的值。
编辑:感谢那些有用的帖子,他们指出我在字典中使用的是字符串,而不是整数或浮点数,我让它起作用了:
def FindPrice(dictionary, idlist):
Price = sum(float(dictionary.get(x,0)) for x in idlist)
return Price
Prices = FindPrice(DictionaryVariable, FunctionThatMakesListofIDs('FileToGetIDsFrom.xml'))
print Prices
发布于 2012-10-01 02:55:45
您的列表2、2、3包含整数,但您的字典的关键字是字符串。我建议您首先使用int键和浮点值创建dict,或者像这样转换它:
>>> d = {'2': '150.99', '3': '99.50', '15': '5.07'}
>>> d = dict((int(k),float(v)) for k, v in d.iteritems())
>>> d
{2: 150.99000000000001, 3: 99.5, 15: 5.0700000000000003}
发布于 2012-10-01 02:55:41
如果未找到该项,get()
将返回None
。BTW您可以将第二个可选参数传递给get()
。现在,如果没有找到id
,则返回该参数(在本例中传递0)。
>>> dic={'2': '150.99', '3': '99.50', '15': '5.07'}
>>> items= ['2', '2', '3']
>>> sum(float(dic.get(x,0)) for x in items) #pass 0 to get in case id is not there
401.48
help(dict.get)
get(...)
D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
https://stackoverflow.com/questions/12664020
复制相似问题