2017-03-15 8 views
1

私はファイルを持っています。どこが3つのラインであり、各ラインは、名前を告げる;スポーツ:ポイントPython - ファイル内の値を合計する方法

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 

のように見えることはCSVモジュールを使用してに

+2

入力し、所望の出力が一致してください。 –

答えて

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 
0

ルック値:

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) 

これは私達を与える:これは選手を記述するdictonariesのリストを生成します

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

try online

0

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}] 
関連する問題