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

时间:2016-02-21 22:25:30

标签: list python-3.x for-loop

我试图独立添加每行嵌套循环以查找平均值。我错过了一个细节,可能会或可能不会破坏我的整个代码。代码应计算给定行分数的平均值,但降低最低等级。

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

如何使for n in score [0]获取每行的平均值而不是仅计算第一行的平均值?我知道scores[0]命令程序只读取第一行,我只是不知道如何更改它。

谢谢

2 个答案:

答案 0 :(得分:1)

请记住,XY problem

# 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))

请记住,Python支持函数式编程,并鼓励程序员尽可能编写pure functions

答案 1 :(得分:0)

语句for n in scores[0]:只会通过第一列。

您想要说的是for n in row:。这将使它遍历每一行,外循环的每个循环一行