【发布时间】:2020-01-03 16:17:17
【问题描述】:
所以我有这个项目,它向用户询问这些文件标题为“天”的 .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 = 3
day1.txt
swimming,1000
fencing,200
athletics,600
gymnastics,1200
tennis,500
day2.txt
diving,600
swimming,1200
tennis,500
rugby,900
handball,500
hockey,2300
trampoline,200
day3.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
【问题讨论】:
-
很抱歉,如果不清楚并且格式不正确,我是堆栈新手
-
如果你想知道为什么我有一个列表,我试图用一个列表来做,然后意识到我需要一本字典,我懒得删除访问代码:)跨度>
标签: python-3.x list file dictionary