【问题标题】:Python - How to sum values in filePython - 如何对文件中的值求和
【发布时间】:2017-03-15 13:39:24
【问题描述】:

所以我有一个文件。哪里有 3 行,每行告诉 Name;sport:points

Kevin;Football:604,196,47;Golf:349,0,0;Tennis:797,426,124
Julia;Football:350,254,1;Golf:242,58,38
Bob;Football:260,18,0

我有一个代码,但我不知道如何计算每项运动的积分

f=open("points.txt", "r")
s=f.readlines()
p=str(s)

for line in s:
    printnum=0
    printnum+=float(line)



    for line in s:
        if p.isdigit():
            total=0
            for number in s:
                total+=int(number)
                print(total)

所以结果应该是这样的

Alvin:
- Football: 278
Kevin:
- Football: 847
- Golf: 349
- Tennis: 1347
Sam:
- Football: 605
- Golf: 338

所以基本上我不知道热求和键值

【问题讨论】:

  • 请使输入和所需的输出匹配。

标签: python list file


【解决方案1】:
from ast import literal_eval as leval

my_dict = {}
for line in s:
    name, *sports = line.split(';')
    my_dict[name] = {sport.split(':')[0]: sum(leval(sport.split(':')[1])) for sport in sports}

for player in my_dict:
    print('{}:'.format(player))
    for sport in my_dict[player]:
        print(' - {}: {}'.format(sport, my_dict[player][sport]))

# Produces:
# Kevin:
#  - Golf: 349
#  - Tennis: 1347
#  - Football: 847
# Julia:
#  - Golf: 338
#  - Football: 605
# Bob:
#  - Football: 278

【讨论】:

    【解决方案2】:

    这将生成描述玩家的字典列表。

    player_list = []
    
    with open("dane") as f_obj:
        for line in f_obj.readlines():
            player_line = line.split(';')
            player_data = {'name': player_line[0]}
    
            for elem in player_line[1:]:
                sport = elem.split(':')
                sport_name = sport[0]
                points = sport[1].split(',')
                sum_points = 0
                for p in points:
                    sum_points += int(p)
    
                player_data[sport_name] = sum_points
    
            player_list.append(player_data)
    
    print(player_list)
    

    现在您只需要根据需要格式化此列表的打印格式。

    这是这个列表的样子:

    [{'name': 'Kevin', 'Golf': 349, 'Football': 847, 'Tennis': 1347}, {'name': 'Julia', 'Golf': 338, 'Football': 605}, {'name': 'Bob', 'Football': 278}]
    

    【讨论】:

      【解决方案3】:

      研究使用 CSV 模块:

      import csv
      
      points = {}
      
      with open('points.txt', 'r') as csvfile:
          reader = csv.reader(csvfile, delimiter=';')
          for row in reader:
              points[row[0]] = {}
              for sport in row[1:]:
                  name = sport[:sport.find(':')] # get the name of the sport
                  scores = sport[sport.find(':')+1:].split(',')
                  total_score = 0
                  for score in scores:
                      total_score = int(score) # add all the scores together
                  points[row[0]][name] = total_score
      print(points)
      
      # Print the resuslts in the order that you want
      for name, sports in sorted(points.items()):
          print(name + ':')
          for sport_name, points in sorted(sports.items()):
              print('-', sport_name + ':', + points)
      

      这给了我们:

      Bob:
      - Football: 0
      Julia:
      - Football: 1
      - Golf: 38
      Kevin:
      - Football: 47
      - Golf: 0
      - Tennis: 124
      

      try online

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-12-21
        • 1970-01-01
        • 2019-01-21
        • 1970-01-01
        • 2021-12-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多