2016-07-19 10 views
0

Python初心者。 ファイルのデータを表示し、各人の合計/平均を計算するにはどうすればよいですか? どのように値をの外にある変数にforを追加するのですか?繰り返しがレコードの数で分割されると、その値は分割されます。ファイルからの平均と合計を計算する

ファイル内のデータは、ユーザーがデータを追加したり、削除したりすることができますので、変化するが、データは次のように構成されています

PersonA 342 454  559 TOTAL AVERAGE 
PersonB 444 100  545 TOTAL AVERAGE 
PersonC 332 567  491 TOTAL AVERAGE 
PersonD 142 612  666 TOTAL AVERAGE 

何をすることができます:私はこのようにそれを提示したい

PersonA;342;454;559; 
PersonB;444;100;545; 
PersonC;332;567;491; 
PersonD;142;612;666; 

私はそれを正しくするためにこの後に書き込みますか?

def show_result(): 
    text_file = open('result.txt', 'r') 

    for line in text_file: 
     if ';' in line: 
      line2 = line.split(";") 
     print line2 

with open("input.txt") as f: 
    for line in f: 

s = """PersonA;342;454;559; 
PersonB;444;100;545; 
PersonC;332;567;491; 
PersonD;142;612;666;""" 

for line in s.split("\n"): 
    p, a, b, c, _ = line.strip().split(";") 
    print("{}\t{}\t{}\t{}\t{}\t{}".format(p, a, b, c, 
     sum([int(a), int(b), int(c)]), 
     sum([int(a), int(b), int(c)])/3)) 

ソリューション:

def show_result(): 
    text_file = open('minigolf.txt', 'r') 

    print "Name,Round1,Round2,Round3" 
    for line in text_file: 
     if ';' in line: 
      line2 = line.split(";")[:-1] 
     print line2 

     line_total = sum(map(int, line2[1:])) 
     line_average = line_total/len(line2[1:]) 
     print "Total: ", line_total 
     print "Average: ", line_average 
+0

合計と平均一人一人のために計算されている方法は?列2,3,4の合計/平均を意味しますか? –

答えて

0

totalあなたは、単に(あなたが「ペルソナ」などが含まれている最初のインデックスを含むようにしたくないと仮定して)んできを計算するには:

そこから
line_total = sum(map(int, line2[1:])) 

は、平均でも簡単です:

line_average = line_total/len(line2[1:]) 

説明:

  • sum機能は、反復可能になります(私たちの目的は、リストとして反復可能と考えるため)し、適切なSUM関数を使用してそのすべての内容を追加します。

  • [1:]はリストスプライシングと呼ばれます。この構文を使用すると、Pythonに、元のリストの内容が1の位置から始まる新しいリストを作成するように指示します。ここでは例のカップルの:次のように

    >>> a = [1, 2, 3] 
    >>> b = [1:] 
    >>> b 
    [2, 3] 
    

具体的な構文は次のとおりです。[start_index : end_index]start_indexまたはend_indexのどちらかが空白のままにすることができ、Pythonはそれぞれリストの先頭や末尾でそれらを記入します。

+0

入力がintではなく文字列であることに注意してください。 –

+0

しかし、これは私が書いたコードとどのように見えるでしょうか?今度はエラーが発生します:ファイル "C:\ Users \ HKI \ Desktop \ test3.py"、行32、show_result line_total = sum(map ValueError:基数10のint()のリテラルが無効です: '' –

2
s = """PersonA;342;454;559; 
PersonB;444;100;545; 
PersonC;332;567;491; 
PersonD;142;612;666;""" 

for line in s.split("\n"): 
    p, a, b, c, _ = line.strip().split(";") 
    print("{}\t{}\t{}\t{}\t{}\t{}".format(p, a, b, c, 
     sum([int(a), int(b), int(c)]), 
     sum([int(a), int(b), int(c)])/3)) 

出力:

PersonA 342  454  559  1355 451.6666666666667 
PersonB 444  100  545  1089 363.0 
PersonC 332  567  491  1390 463.3333333333333 
PersonD 142  612  666  1420 473.3333333333333 

編集:あなたは、ファイルから読み込みたい場合

、あなたはこれを行うことができます。私はどうだろうか

with open("input.txt") as f: 
    for line in f: 
     # same as above: split the line, etc. 
+0

これはファイルからデータを取得しますか?データはPersonAのようにresult.txtに格納されます; 342; 454; 559; –

+0

はい、ファイルから行を読みやすいです。 –

+0

私の説明は少し不明かもしれません。ユーザーはresult.txt内のデータを削除して追加することができるため、PersonAは存在しない可能性がありますが、PersonQは1回限り可能ですが、次のPersonQはない可能性があります。 ファイルからデータを取得し、それを別の行に取得する方法と、時折ファイルに存在する人物がわからないときの合計/平均を計算する方法はありますか? –

0

これを。つまり、これをPyhtonで行う方法はたくさんあります。私は操作のこのタイプのpandasライブラリを使用

import pandas as pd 

df = pd.read_csv('result.txt', sep=';',header=None) 
del df[4] 
df['AVERAGE'] = df[[1,2,3]].mean(axis = 1) 
df['TOTAL'] = df[[1,2,3]].sum(axis = 1) 

出力:

0   1  2  3  AVERAGE  TOTAL 
0 PersonA  342  454  559  451.666667 1355 
1 PersonB  444  100  545  363.000000 1089 
2 PersonC  332  567  491  463.333333 1390 
3 PersonD  142  612  666  473.333333 1420 
0

これは一人あたり、そして人々の任意の数の任意の値のために動作します:

from collections import defaultdict 

def myprint(lines): 
    sum_dict = defaultdict(lambda: ([], 0, 0)) 

    for line in lines: 
     data = line.strip().split(";") 
     person = data[0].strip() 
     values = [int(i) for i in data[1:] if i] 
     sum_dict[person] = (values + sum_dict[person][0], sum(values)+sum_dict[person][1], len(values)+sum_dict[person][2]) 

    for person in sorted(sum_dict): 
     values, total, nb = sum_dict[person] 
     print "{}\t{}\t{}\t{}".format(person, '\t'.join([str(i) for i in values]), total, total/nb) 

if __name__ == '__main__': 

    import os 
    if os.path.exists('result.txt'): 
     with open('result.txt') as input: 
      lines = input.readlines() 
    else: 
     s = """PersonA;342;454;559; 
       PersonB;444;100;545; 
       PersonC;332;567;491; 
       PersonD;142;612;666;""" 
     lines = s.split('\n') 

    myprint(lines)