因此,我有一个项目,它要求用户提供.txt文件的数量,这些文件的标题是“日”,然后是按升序排列的数字。代码中的格式是体育/活动(键),然后是逗号和从事这项运动的人数(值)。我想要的是它从文本文件中给出所有运动的输出,如果活动(键)被复制,那么它就会将做它的人加起来(值)。最重要的是,我想要的是所有参与的人(所有的价值加在一起)。
days = int(input("How many days of records do you have? "))
i = 0
list1 = []
d = {}
for i in range(days):
i += 1
file = 'day' + str(i)
f = open(file + '.txt')
a = []
for line in f:
line = line.replace(',' , ' ')
list1.append(line)
words = line.split()
d[words[0]] = words[1]
a.append[words[1]]
stripped_line = [s.rstrip() for s in d]
for key,value in d.items() :
print (key + "," + value)
print("In total:", a, "attendees.") 输入
User_input = 3day1.txt
swimming,1000
fencing,200
athletics,600
gymnastics,1200
tennis,500day2.txt
diving,600
swimming,1200
tennis,500
rugby,900
handball,500
hockey,2300
trampoline,200day3.txt
swimming,400
gymnastics,1200
fencing,100
diving,400
tennis,600
rugby,600预期输出
swimming: 2600
fencing: 300
athletics: 600
gymnastics: 2400
tennis: 1600
diving: 1000
rugby: 1500
handball: 500
hockey: 2300
trampoline: 200
In total: 13000 attendees.电流输出
swimming,400
fencing,100
athletics,600
gymnastics,1200
tennis,600
diving,400
rugby,600
handball,500
hockey,2300
trampoline,200发布于 2019-08-30 12:05:31
这是一种使用collections.defaultdict的方法。
Ex:
from collections import defaultdict
days = int(input("How many days of records do you have? "))
result = defaultdict(int)
for i in range(days):
with open("day{}.txt".format(i)) as infile:
for line in infile:
key, value = line.strip().split(",")
result[key] += int(value)
for key,value in result.items():
print (key + "," + str(value))
print("In total: {} attendees.".format(sum(result.values())))https://stackoverflow.com/questions/57726241
复制相似问题