简体   繁体   English

遍历列表-Python 3

[英]Iterating through a list - Python 3

I have the following code for opening a file, sorting it by a column and then appending the mean to it. 我有以下代码用于打开文件,将其按列排序,然后将均值附加到它。 However, I can not get the for loop to iterate through each of the rows... x = list(map(int, sortedlist[1:][1][1:])) I tired changing the 1's to a counter variable called y but it didn't work. 但是,我无法获得for循环来遍历每一行... x = list(map(int, sortedlist[1:][1][1:]))我厌倦了将1改为计数器变量叫y,但是没有用。

Here is what the file looks like and code below. 这是该文件的外观以及下面的代码。

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)

You want to get the mean of each sublist so use each sublist not the sortedlist: 您想要获取每个子列表的平均值,因此请使用每个子列表而不是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]]

If you want the mean of all the lists combined you can use itertools.chain extracting all the elements/ints from each row and chaining them together: 如果要组合所有列表的均值,可以使用itertools.chain从每一行中提取所有元素/整数并将其链接在一起:

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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM