遍历列表 - Python 3

Iterating through a list - Python 3

我有以下代码用于打开一个文件,按列对其进行排序,然后将平均值附加到它。但是,我无法让 for 循环遍历每一行...x = list(map(int, sortedlist[1:][1][1:])) 我厌倦了将 1 更改为名为 y 的计数器变量,但它不起作用。

这是文件的样子和下面的代码。

Lee,6,3,4
John,11,10,8
Luke,2,3,8
Terry,4,7,6


import sys, csv, operator
from statistics import mean

#Sorts list
reader = csv.reader(open("O:\Class 1.csv"), delimiter=",")
sortedlist = sorted(reader, key=operator.itemgetter(1), reverse=True)

#Appends average to the end of each row.
for sublist in sortedlist:
    x = list(map(int, sortedlist[1:][1][1:])) #HERE'S THE PROBLEM!
    x = mean(x)
    sublist.append(x)
    print(sublist) 
print(sortedlist)

您想获得每个子列表的平均值,因此使用每个子列表而不是排序列表:

for sublist in sortedlist:
    x = mean(map(int, sublist[1:])) #HERE'S THE PROBLEM!
    sublist.append(x)
    print(sublist)
print(sortedlist)

[['Lee', '6', '3', '4', 4.333333333333333], ['Terry', '4', '7', '6', 5.666666666666667], ['Luke', '2', '3', '8', 4.333333333333333], ['John', '11', '10', '8', 9.666666666666666]]

如果您想要合并所有列表的平均值,您可以使用 itertools.chain 从每一行中提取所有 elements/ints 并将它们链接在一起:

from itertools import chain

x = mean(map(int, chain.from_iterable(row[1:] for row in sortedlist)))
print(x)
6.0


x = list(map(int, chain.from_iterable(row[1:] for row in sortedlist))
print(x)
[6, 3, 4, 4, 7, 6, 2, 3, 8, 11, 10, 8]