需要帮助理解为什么这个值保持为1? Python CSV

时间:2015-04-25 16:45:55

标签: python csv

因此,这段代码应该打开csv文件,从第1-3列(不是0)获取值。一旦它获得了每行及其3列的值,就应该将这些值加起来并除以3.我认为这段代码可行但是每行中添加3列似乎并不是工作。如果有人能告诉我为什么以及如何解决这个问题,那就太棒了,谢谢。我很确定问题出在for index, summedValue in enumerate (sums):具体来说," summedValue"值。

if order ==("average score"):
    askclass = str(input("what class?"))
    if askclass == ('1'):
            with open("Class1.csv") as f:
                columns = f.readline().strip().split(" ")
                sums = [1] * len(columns)

                for line in f:
                    # Skip empty lines
                    if not line.strip():
                         continue

                    values = line.split(" ")
                    for i in range(1,len(values)):
                        sums[i] += int(values[i])

                for index, summedValues in enumerate (sums):    
                  print (columns[index], 1.0 * (summedValues) / 3)

2 个答案:

答案 0 :(得分:0)

使用

1, 2, 3
4, 2, 3
4, 5, 3
1, 6, 3
1, 6, 6
6, 2, 3

作为Class1.csv 和

askclass = str(input("what class?"))
if askclass == ('1'):
  with open("Class1.csv") as f:
    columns = f.readline().strip().split(",")
    sums = [1] * len(columns)
    for line in f:
      # Skip empty lines
      if not line.strip():
        continue
      values = line.split(",")
      for i in range(1,len(values)):
        sums[i] += int(values[i])
for index, summedValues in enumerate (sums): 
  print (columns[index], 1.0 * (summedValues) / 3)

我获得了预期的结果:

what class?1
('1', 0.3333333333333333)
(' 2', 7.333333333333333)
(' 3', 6.333333333333333)

[更新] 观察:

  1. 已定义的广告sums = [1] * len(columns)包含长度列,但您忽略了操作中的第一列,因此sum [0]的值始终为1,似乎没必要。
  2. 对于浮点除法,summedValues / 3.0代替1.0 * (summedValues) / 3
  3. 就足够了

    也许这就是你想要的

    for line in f:
        # Skip empty lines
        if not line.strip():
             continue
    
        values = line.split(" ")
        for i in range(1,len(values)):
            sums[i] += int(values[i])
    
    for index, summedValues in enumerate (sums):    
      print (columns[index], 1.0 * (summedValues) / 3)
    

答案 1 :(得分:0)

from statistics import mean
import csv

with open("Class1.csv") as f:
    # create reader object
    r = csv.reader(f)
    # skip headers
    headers = next(r)
    # exract name from row and use statistics.mean to average from row[1..
    # mapping scores to ints
    avgs = ((row[0], mean(map(int, row[1:]))) for row in r)
    # unpack name and average and print
    for name, avg in avgs:
        print(name,avg)

除非您在csv文件中写入空行,否则不会有任何内容,不确定标题是如何适合它的,但如果需要,您可以使用它。

您也可以使用python 3中的*语法解压缩,我觉得这样更好一点:

avgs = ((name, mean(map(int, row))) for name, *row in r)
for name, avg in avgs:
    print(name,avg)

要按顺序排序,请使用reverse = True从最高到最低排序:

from statistics import mean
import csv
from operator import itemgetter

with open("Class1.csv") as f:
    r = csv.reader(f)
    avgs = sorted(((name, mean(map(int, row))) for name, *row in r),key=itemgetter(1),reverse=True)
    for name, avg in avgs:
        print(name,avg)

传递key=itemgetter(1)意味着我们按第二个子元素排序,这是每个元组的平均值。