Python Dictonary - 两个文件 - 根据键值乘以值/属性

时间:2016-11-15 03:06:25

标签: python

我一直在努力为我的朋友解决问题。但是,它似乎让我感到烦恼,因为我无法映射两个文件中的键值。

问题描述:

第一个文件(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)

问题发生在if条件下,因为它没有进入循环。修正?

3 个答案:

答案 0 :(得分:0)

我没有运行你的代码,但是在你做的时候似乎:

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

您正在向键添加数组而不是标量 - >像Apple:[1.3]而不是Apple:1.3

然后在最后一个循环中,执行类似

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

答案 1 :(得分: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中的所有键并获取数量和价格,将它们相乘并更新总数。

答案 2 :(得分: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
相关问题