簡體   English   中英

遍歷列表-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)

您想要獲取每個子列表的平均值,因此請使用每個子列表而不是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從每一行中提取所有元素/整數並將其鏈接在一起:

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