2016-03-19 9 views
-3

複数の整数リストの平均を計算するにはどうすればよいですか?複数の整数リストの平均を計算するにはどうすればよいですか?

このプログラムでテキストファイルのデータの平均を計算しようとすると、問題が発生します。

だから、これは私のコードです:

ボブ、8,5,7

ディラン、5:ここで

import string 
from operator import itemgetter 
Options=("alphabetical order","highest to lowest","average score") 
Option=raw_input("Which order do you want to output?" + str(Options)) 
choices=("Class 1","Class 2", "Class 3") 
file = open("Class1.txt","r") 
#Highest to Lowest 
lines = file.readlines() 
loopcount = len(lines) 
for i in range(0,loopcount): 
    poszerostring = lines.pop(0) 
    new = str(poszerostring) 
    new1 = string.strip(new,'\n') 
    tempArray = new1.split(',') 
    resultsArray = [tempArray.append(poszerostring)] 
    name = tempArray.pop() 
    resultsArray.append(int(tempArray.pop())) 
    resultsArray.append(int(tempArray.pop())) 
    resultsArray.append(int(tempArray.pop())) 
    resultsArray.remove(None) 
    printedArray = resultsArray 
    print printedArray 
if Option == "average score": 
     average = 0 
     sum = 0  
     for n in printedArray: 
      sum = sum(str(printedArray)) 
     average = sum/3 
     print average 

は、テキストファイルにあるデータであり、 、8,2

ジャック、1,4,7

ジェイ(Jay)、3,8,9

+0

@gollumbo、なぜあなたの編集ですべてのコードを削除しましたか? –

+0

GCSEのこの部分ですか? –

+1

この質問の内容を削除したりロールバックしたりすることは、ばかげている。あなたは、一般に見られるように問題を掲示しています。まともな回答を得て、後であなたの痕跡を消してください。 @Peterの答えだけでなく、質問も[Googleのキャッシュ](http://webcache.googleusercontent.com/search?q=)に既に入っています。キャッシュ:Cp79m7vYBlwJ:stackoverflow.com/questions/36100687/how-to-calculate-the-average-of-multiple-lists-of-integers+&cd=1&hl=de&ct=clnk&gl=de)。 – altocumulus

答えて

2

あなたは、ほとんどのコードでホイールを再発明しています。私はファイルを読むためにcsvパッケージを使用すると、コードがより洗練されたものになります。 Documentation here

import csv 

with open('Class1.txt') as csv_file: 
    csv_reader = csv.reader(csv_file, delimiter=',') 
    for row in csv_reader: 
     name = row[0] # first value on each row is a name 
     values = [int(value) for value in row[1:]] # make sure the other values are read as numbers (integers), not strings (text) 
     average = sum(values)/len(values) # note that in Python 2 this rounds down, use float(sum(values))/len(values) instead 
     print('{}: {}'.format(name, average)) 

さらにいくつかのポインタ:

  • 応じTOTのPEP8変数(のようなOptionsは大文字で始めるべきではありません。クラスべきである。
  • あなたは一度だけの変数を使用している場合、一般的にloopcountのように `for i in range(0、len(lines));
  • のように実際にはループカウンタは必要ありません。iを使用してください。for line in lines:;
  • 行は、関数sumを値で上書きし、スクリプト内で関数sumを使用できなくします。既存の関数名と同じ変数名を使うのは避けてください。
  • sum(str())は、数字ではなく文字列を追加しようとしているため、期待通りに機能しません。
  • 私はwith open(file_name) as file_handler:を使用しています。これはファイルを開き、コードブロックの最後に自動的にファイルを閉じて、ファイルをもう一度閉じるのを忘れるのを防ぎます。 withhereの詳細。
+0

良い答えは、あなたがなぜファイルを開くために使うのか説明したいかもしれません –

関連する問題