2016-11-15 68 views
0

我一直在試圖爲我的朋友解決問題。但是,這似乎是bug我,因爲我無法映射兩個文件中的鍵值。Python Dictonary - 兩個文件 - 根據關鍵值乘以值/屬性

問題描述:

第一個文件(sales.txt)的內容:

Apple 30 
Grape 90 
Cup 35 
Toy 100 
Apple 50 
Grape 51 
Toy 83 

第二個文件(price.txt)的內容:

Apple 1.3 
Grape 0.99 
Cup 1.5 
Toy 15 

的工作就是打印總價格。在這種情況下,我們需要打印3041.09。

我知道一個事實,即我們需要使用字典並根據關鍵字映射兩個字典。因此,我根據自己的知識編寫了代碼。 (非常抱歉,如果它是愚蠢的!)

f = "sales.txt" 
d={} 
for line in open(f): 
    a=line.split() 
    key, values = str(a[0]), int(a[1]) 
    d.setdefault(key, []).append(int(values)) 
print(d) 

d = dict((key, sum(values)) for key, values in d.items()) 

print(d) 

g = "price.txt" 
dy={} 
for line in open(g): 
    b=line.split() 
    unit, price = str(b[0]), float(b[1]) 
    dy.setdefault(unit, []).append(float(price)) 
print(dy) 

total = 1.0 

for i in range(0, len(d)): 
    if d[key] == dy[unit]: 
     total = d.values*dy.price 

print(total) 

問題發生在條件,因爲它沒有進入循環。更正?

+0

,你永遠不更新'key'或'unit' 。 – James

+0

你能簡單解釋一下嗎? – HackersBusy

回答

0

,這在某種程度上使用第一循環的運行計數,只是總結在第二循環中總被簡化:

with open("sales.txt") as f: 
    d = {} 
    for line in f: 
     key, value = line.split() 
     d[key] = d.get(key, 0) + int(value) 

with open("price.txt") as g: 
    total = sum(d[key] * float(price) for line in g for key, price in [line.split()]) 
print(total) 
#3041.09 
在過去的for循環
0

我沒有運行代碼,但它似乎當你做:

dy.setdefault(unit, []).append(float(price)) 

要添加到關鍵的數組,而不是一個標量 - >像蘋果:[1.3],而不是蘋果的:1.3

然後在最後一環,這樣做

for item,count in d.items(): 
    total += count*dy[item] 
0

相反的:

total = 1.0 

for i in range(0, len(d)): 
    if d[key] == dy[unit]: 
     total = d.values*dy.price 

用途:

# the total should start at 0. 
total = 0.0 

for k in d: 
    total = total + d[k]*dy[k] 

這會遍歷所有的鍵在d搶數量和價格,它們相乘並更新總。