将字典中的项目列表相乘

2024-04-23 11:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,每本字典有两个数字。我需要将这些数字相乘,并保持字典中所有键的运行总数。我一直收到一个打字错误:

sub = v1 * v2
TypeError: can't multiply sequence by non-int of type 'list'

我试着让它漂浮,但后来我得到:

v1= float(c.get(k,v[0]))
TypeError: float() argument must be a string or a number, not 'list'

代码如下:

change = {'penny': [.01,57], 'nickel':[.05,34],'dime':[.1,42], 'quarter':  [.25,19],'half dallar':[.5,3],'one dollar bill':[1,24],'five dollar bill':[5,7],'ten dollar bill':[10,5],'twenty dollar bill':[20,3]}

def totalAmount(c):
   total = 0
   for k, v in c.items():
       v1= c.get(k,v[0])
       v2= c.get(k,v[1])

       sub = v1 * v2
       total = total + sub


totalAmount(change)
print("Total in petty cash: $" + total)

Tags: inget字典数字floatchangelistv2
3条回答

试试这个:

change = {'penny': [.01,57], 'nickel':[.05,34],'dime':[.1,42], 'quarter':  [.25,19],'half dallar':[.5,3],'one dollar bill':[1,24],'five dollar bill':[5,7],'ten dollar bill':[10,5],'twenty dollar bill':[20,3]}

def totalAmount(c):
   total = 0
   for k, v in c.items():
       sub = v[0] * v[1]
       total = total + sub
   return total


t = totalAmount(change)
print(t)

输出将是

181.72

代码的问题是v1= c.get(k,v[0])。 如果您想使用get,您应该将其更改为v1= c.get(k)[0],但是当您使用.items()时,您不需要使用getv将是每个迭代中所需的数组。你知道吗

v1= c.get(k,v[0])
v2= c.get(k,v[1])

在这种情况下,v1v2都被设置为vc.get(i)返回c[i],因此c[k]自然会返回相应的值v。相反,只需将您的列表按如下方式拆分:

v1, v2 = v

dict.get方法的第二个参数用于默认值,而不是用于进一步的值检索。你知道吗

您可以像这样解压子列表的值:

for k, (v1, v2) in c.items():
    sub = v1 * v2
    total = total + sub

相关问题 更多 >