【问题标题】:How To Add 2 values in a dictionary together if the key is duplicated?如果键重复,如何在字典中添加 2 个值?
【发布时间】: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


【解决方案1】:

这是使用collections.defaultdict 的一种方法。

例如:

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())))

【讨论】:

  • with open("day{}.txt".format(i)) as infile:此代码检查'day0.txt,但文件名从'day1.txt'开始
  • 使用for i in range(1, days+1):
  • print(key + "," + value) TypeError: must be str, not int
  • 其实是print (key + "," + str(value))
  • 很抱歉一直打扰你,但现在它给出了双倍的答案
猜你喜欢
  • 2022-01-18
  • 2022-11-03
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 2020-01-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-06
相关资源
最近更新 更多