2016-09-29 48 views
1
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}} 

我試圖總結在所有的水果和乘上B.我無法做這方面的一個就是數字數組和B是字典。這是我感到困惑的地方。我是一個新的Python用戶。 A中的數字與水果的相同位置(A中的第一個數字是蘋果的數量)。這涉及使用總和(A)?總結了一個數組,然後乘以一個字典

對不起,缺乏細節的人。這是一些清晰的。我有水果,每個人都有不同類型的水果。我想總結所有的每種水果類型的值在B這樣的,我得到:

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

現在,我想多這些數字,由A,但同時要注意的是,第一個數字在A,是蘋果,然後是橙色,等等,以得到一個新的數組:

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

的問題是不明確的。這些數據的預期結果是什麼? – zvone

+0

顯示數學,你可以手工操作,我們將能夠提供幫助 – ccarton

+0

謝謝。我現在正在努力更新我的問題。 –

回答

3

假設你想multply成果的總和每個人(在B)由成本A,你可以做以下列表理解:

>>> [cost * sum(B[fruit].values()) for cost, fruit in zip(A, Fruits)] 
[48, 18, 160, 104] 
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] 

我猜?

+0

我沒有看到任何其他的方式來做到這一點,除非他們想要名稱的總和(例如'比爾','揚'和'弗蘭克')。 –

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 
相關問題