简体   繁体   English

在python中使用for循环和嵌套列表

[英]Using for loops and nested lists in python

I am trying to add each row of nested loop independently in order to find averages. 我试图独立添加嵌套循环的每一行,以求平均值。 I am missing a detail which may or may not derail my whole code.The code should compute the average of a given row of scores but drops the lowest grade. 我错过了一个细节,该细节可能会或可能不会破坏我的整个代码。该代码应该计算给定分数行的平均值,但会降低最低成绩。

def printAverages():
scores = [[100,100,1,100,100],
          [20,50,60,10,30],
          [0,10,10,0,10],
          [0,100,50,20,60]]
total = 0
minValue = 100
counter = -1
for row in scores:
    counter = counter + 1
    for n in scores[0]:
        total = total+n
        if minValue > n:
            minValue = n
    total = total - minValue
    print("Average for row",counter,"is",total)
    total = 0

How do i make it so for n in score [0] takes the average of each row instead of only computing the average of the first row? 我如何才能使for n in score [0]取每一行的平均值,而不是仅计算第一行的平均值? I know that scores[0] commands the program to only read the first row, I just don't know how to change it. 我知道scores[0]命令程序仅读取第一行,我只是不知道如何更改它。

Thank you 谢谢

Remember, the XY problem . 请记住, XY问题

# Sum of a list of numbers divided by the number of numbers in the list
def average(numbers):
    return sum(numbers)/len(numbers)

# This is your data
scores = [[100,100,1,100,100],
          [20,50,60,10,30],
          [0,10,10,0,10],
          [0,100,50,20,60]]

# enumerate() allows you to write FOR loops naming both the list element and its index
for (i, row) in enumerate(scores):
    print("Average for row ", i, "is ", average(row))

Keep in mind that Python supports functional programming and encourages the programmer to write pure functions when possible! 请记住,Python支持函数式编程,并鼓励程序员在可能的情况下编写纯函数

the statement for n in scores[0]: will only go through the first column. for n in scores[0]:的语句将仅通过第一列。

What you want it to say is for n in row: . 您想要说的是for n in row: That will have it go through each row, one row per loop of the outer loop 它将遍历每一行,外循环每循环一行

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

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