对数组求和,然后乘以字典

时间:2016-09-29 19:20:01

标签: python dictionary

Fruits = ['apple', 'orange', 'banana', 'kiwi']

A = [4,  3,  10,  8]

B = {'apple': {'Bill': 4, 'Jan': 3, 'Frank': 5},
     'orange': {'Bill': 0, 'Jan': 1, 'Frank': 5},
     'banana': {'Bill': 8, 'Jan': 6, 'Frank': 2},
     'kiwi': {'Bill': 4, 'Jan': 2, 'Frank': 7}}

我试图总结A的所有成果并将其乘以B.我无法做到这一点A是一个数字数组而B是字典。这是我感到困惑的地方。我是一个新的Python用户。 A中的数字与Fruit相同(A中的第一个数字是苹果数)。这会涉及使用sum(A)吗?

对不起,人们缺乏细节。这里有一些清晰度。我有水果,我有很多水果,每个人都根据类型。我想要总结B中每种水果类型的所有值,以便得到:

 apple = 12
 orange = 6
 banana = 16
 kiwi = 13

现在,我希望通过A将这些数字加倍,但请记住,A中的第一个数字是苹果,然后是橙色,依此类推以获得新数组:

 Solution = [48,18,160,104] #solution order is apple, orange, banana, kiwi

3 个答案:

答案 0 :(得分:3)

假设您希望将每个人的成果总和(B)乘以A中的成本,您可以执行以下列表理解:

>>> [cost * sum(B[fruit].values()) for cost, fruit in zip(A, Fruits)]
[48, 18, 160, 104]

答案 1 :(得分:0)

fruit_costs = {fruit_name:fruit_cost for fruit_name,fruit_cost in zip(Fruits,A)
for fruit in Fruits:
    print "Fruit:",fruit,"=",sum(B[fruit].values())*fruit_costs[fruit]

我想?

答案 2 :(得分:0)

将所有内容合并为一个大词典;这里的一切都只是水果的特性:

>>> for i, fruit in enumerate(fruits):
>>>     B[fruit]['cost'] = A[i]
>>> B
{'banana': {'Frank': 2, 'Jan': 6, 'Bill': 8, 'cost': 10}, 'apple': {'Frank': 5, 'Jan': 3, 'Bill': 4, 'cost': 4}, 'orange': {'Frank': 5, 'Jan': 1, 'Bill': 0, 'cost': 3}, 'kiwi': {'Frank': 7, 'Jan': 2, 'Bill': 4, 'cost': 8}}

将“B”重命名为“水果”(失去“水果”的旧价值):

>>> fruits = B

计算每种水果的水果成本:

>>> for fruitname in fruits:
...     fruit = test.B[fruitname]
...     fruit['total'] = fruit['Frank'] + fruit['Bill'] + fruit['Jan']
...     fruit['total cost'] = fruit['cost'] * fruit['total']
... 
>>> fruits
{'banana': {'total': 16, 'Frank': 2, 'Jan': 6, 'total cost': 160, 'Bill': 8, 'cost': 10}, 'apple': {'total': 12, 'Frank': 5, 'Jan': 3, 'total cost': 48, 'Bill': 4, 'cost': 4}, 'orange': {'total': 6, 'Frank': 5, 'Jan': 1, 'total cost': 18, 'Bill': 0, 'cost': 3}, 'kiwi': {'total': 13, 'Frank': 7, 'Jan': 2, 'total cost': 104, 'Bill': 4, 'cost': 8}}

计算总费用:

>>> total = sum(fruits[fruit]['total cost'] for fruit in fruits)

或者,如果你是Python的新手,那么最后一行是不方便的,你可以将它扩展为:

>>> total = 0
>>> for fruitname in fruits:
...     fruit = fruits[fruitname]
...     total += fruit['total cost']
... 

无论哪种方式:

>>> total
330