Hi, i got stuck with the below code, while I was trying to find solution for the question:Find all persons based on quantity of books sold.
below is the content of the file 1711.txt
- 大卫书 05 沃尔玛
- 艾米莉书 10 克罗格
- 杰森食品 11 目标
- 大卫食品 20 克罗格
- eva布13目标
- 大卫书 5 沃尔玛
输出应该类似于:david sell 10 books to walmart
eva 卖出了 13 件衣服达到目标
大卫向克罗格出售了 20 种食物
下面是我编写的代码,请协助我使用正确的代码以显示正确的结果,谢谢!
d={}
p={}
q={}
with open("1711.txt","r") as f:
for line in f:
a=line.split()
l,m,n,o=str(a[0]), str(a[1]), int(a[2]), str(a[3])
d.setdefault(l,[]).append(n)
p.setdefault(m,[]).append(n)
q.setdefault(o,[]).append(n)
d=dict((key,sum(val)) for key,val in d.items())
print (d)
print("----------------------")
p=dict((keys,sum(values)) for keys,values in p.items())
print (p)
print("--------------------")
q=dict((keeys,sum(valu)) for keeys,valu in q.items())
print (q)
print("----------------------------")
for k, v in d.items():
print("number of itmes sold by {} is {}".format(k,v))
print("------------------------------")
for k, v in q.items():
print("number of itmes in {} is {}".format(k,v))
print("------------------------------")
for k, v in p.items():
print("total number of {} sold is {}".format(k,v))
print("------------------------------")
听起来你想要一些嵌套字典。顶层的键应该是所有名称,值应该是另一个字典。
这些字典应该有项目的键,值应该是另一个字典。
最后,这些字典应该具有包含商店的键,并且值应该是已出售给该商店的数量。
那么如果你输入: sales_dict["david"]["book"]["target"] 它会为你输出 10。
编辑:这是创建字典的要点。我想你应该引用https://docs.python.org/3/tutorial/datastructures.html#dictionaries如果您仍然遇到问题。
d = {}
for line in f:
a=line.split()
l,m,n,o=str(a[0]), str(a[1]), int(a[2]), str(a[3])
if l not in d:
d[l] = {}
if m not in d[l]:
d[l][m] = {}
if n not in d[l][m]:
d[l][m][n] = 0
d[l][m][n] += int(o)
我是一名优秀的程序员,十分优秀!