我一直在試圖爲我的朋友解決問題。但是,這似乎是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)
問題發生在條件,因爲它沒有進入循環。更正?
,你永遠不更新'key'或'unit' 。 – James
你能簡單解釋一下嗎? – HackersBusy