计算 Python 中某些列表值的平均值

Calculating mean of certain list values in Python

我一直在尝试计算 .csv 文件每一行中第三、第四和第五个值的平均值,但我的程序只会计算第一行而不是每一行。 例如,这段代码:

file=open("file.csv", "r")
data=csv.reader(file)

data=[[row[0],row[1],eval(row[2]),eval(row[3]),eval(row[4])] for row in data]

from statistics import mean

numbers=[row[2],row[3],row[4]]
newdata=[[row[0],row[1],mean(numbers)] for row in data]
sort=sorted(newdata,key=operator.itemgetter(2), reverse=True)


for eachline in sort:
    print(eachline)

file.close()

...读取此文件:

Phillip,Turner,1,4,10
Sarah,Connor,4,8,1
Alex,Grice,2,10,3
Cheesy,Wotsit,3,2,6
Chris,Mclaughlin,10,9,8
Alison,Humphries,4,2,6

并产生这个:

['Phillip', 'Turner', 4.0]
['Sarah', 'Connor', 4.0]
['Alex', 'Grice', 4.0]
['Cheesy', 'Wotsit', 4.0]
['Chris', 'Mclaughlin', 4.0]
['Alison', 'Humphries', 4.0]

实际上它不是第一行的平均值,它是最后一行的平均值。在第一个列表理解之后,行采用最后一行的值,当您使用行 [2] 创建数字列表时,您使用最后一行的值创建一个静态列表。

您可以通过计算正确数字的平均值来更正:

file=open("file.csv", "r")
data=csv.reader(file)

data=[[row[0],row[1],eval(row[2]),eval(row[3]),eval(row[4])] for row in data]

from statistics import mean

newdata=[[row[0],row[1],mean([row[2],row[3],row[4]])] for row in data]
sort=sorted(newdata,key=operator.itemgetter(2), reverse=True)


for eachline in sort:
    print(eachline)

file.close()
import csv
averages = []
with open("file.csv", "r") as f:
  reader = csv.reader(f, delimiter=",")
  for row in reader:
    values = map(int, row[2:])
    averages.append(row + [sum(values) / float(len(values))])
for avg in sorted(averages,key=lambda x: x[-1]):
  print avg    

打印

['Cheesy', 'Wotsit', '3', '2', '6', 3.6666666666666665]
['Alison', 'Humphries', '4', '2', '6', 4.0]
['Sarah', 'Connor', '4', '8', '1', 4.333333333333333]
['Phillip', 'Turner', '1', '4', '10', 5.0]
['Alex', 'Grice', '2', '10', '3', 5.0]
['Chris', 'Mclaughlin', '10', '9', '8', 9.0]

您必须对每一行执行此操作 numbers=[row[2],row[3],row[4]]。不止一次。 你可以这样做:

In [511]: data = csv.reader(open('../a.csv'))

In [512]: x = [[row[0], row[1], np.mean(map(float, row[2:]))] for row in data]

In [513]: x
Out[513]: 
[['Phillip', 'Turner', 5.0],
 ['Sarah', 'Connor', 4.333333333333333],
 ['Alex', 'Grice', 5.0],
 ['Cheesy', 'Wotsit', 3.6666666666666665],
 ['Chris', 'Mclaughlin', 9.0],
 ['Alison', 'Humphries', 4.0]]

In [514]: sorted(x, key=lambda v: v[2], reverse=True)
Out[514]: 
[['Chris', 'Mclaughlin', 9.0],
 ['Phillip', 'Turner', 5.0],
 ['Alex', 'Grice', 5.0],
 ['Sarah', 'Connor', 4.333333333333333],
 ['Alison', 'Humphries', 4.0],
 ['Cheesy', 'Wotsit', 3.6666666666666665]]

这样试试:

with open('your_file') as f:
    for x in f:
        x = x.strip().split()
        print x + [sum(map(int,x[2:]))/float(len(x[2:]))]

newdata=[[row[0],row[1],mean(numbers)] for row in data]

应该是

newdata=[[row[0],row[1],mean(row[2:])] for row in data]