如何在python中使用for/while循环在嵌套列表中查找avg

如何在python中使用for/while循环在嵌套列表中查找avg,python,Python,错误: 平均值列表([[4,6],[5,5]] 回溯(最近一次呼叫最后一次): 平均值=总和(项目[i])/len(项目[i]) builtins.TypeError:“int”对象不可编辑 我想知道如何修复它,非常感谢! 在while循环中还有其他方法吗?在for循环中,您想做什么?您只需按值而不是索引迭代M。该行用于范围内的i(len(item)):导致了您的错误。不需要内部for循环 def average_list(M): '''(list of list of int) -> l

错误: 平均值列表([[4,6],[5,5]] 回溯(最近一次呼叫最后一次): 平均值=总和(项目[i])/len(项目[i]) builtins.TypeError:“int”对象不可编辑

我想知道如何修复它,非常感谢!
在while循环中还有其他方法吗?

在for循环中,您想做什么?您只需按值而不是索引迭代
M
。该行
用于范围内的i(len(item)):
导致了您的错误。不需要内部for循环

def average_list(M):
'''(list of list of int) -> list of float

Return a list of floats where each float is the average of 
the corresponding list in the given list of lists.

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]

'''
L = []

for item in M:
    for i in range(len(item)):
        avg = sum(item[i])/len(item[i])
        L.append(avg)
return L
但是你应该使用列表理解。在我看来,这将是解决您的问题的最规范的方法,更不用说:


在for循环中,您想做什么?您只需按值而不是索引迭代
M
。该行
用于范围内的i(len(item)):
导致了您的错误。不需要内部for循环

def average_list(M):
'''(list of list of int) -> list of float

Return a list of floats where each float is the average of 
the corresponding list in the given list of lists.

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]

'''
L = []

for item in M:
    for i in range(len(item)):
        avg = sum(item[i])/len(item[i])
        L.append(avg)
return L
但是你应该使用列表理解。在我看来,这将是解决您的问题的最规范的方法,更不用说:


您的错误是
项[i]
是单个元素,不能
求和
len
。您不需要那个内部循环,for循环比while循环更可取,因为您有一个有限的集合

如果使用Python3,您可以使用mean函数,并将其映射到列表列表上

>>> def average_list(M):
        return [sum(sublist)/len(sublist) for sublist in M]

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]
>>> 

借用您的错误是
项[i]
是单个元素,您不能
求和
len
。您不需要那个内部循环,for循环比while循环更可取,因为您有一个有限的集合

如果使用Python3,您可以使用mean函数,并将其映射到列表列表上

>>> def average_list(M):
        return [sum(sublist)/len(sublist) for sublist in M]

>>> average_list([[4, 6], [5, 5]])
[5.0, 5.0]
>>> 
借用python 3中的

from statistics import mean

def average_list(M):
    return list(map(mean, M)) 
或者在python 2中:

lst=[[4, 6], [5, 5]]
list(map(lambda x: sum(x)/len(x), lst))
Out[104]: [5.0, 5.0]
在python 3中:

from statistics import mean

def average_list(M):
    return list(map(mean, M)) 
或者在python 2中:

lst=[[4, 6], [5, 5]]
list(map(lambda x: sum(x)/len(x), lst))
Out[104]: [5.0, 5.0]

我只能使用for循环或while循环来执行此操作。这很好。我已经解释了错误的原因。我认为
map
的源代码使用for循环,所以如果有人抱怨,就这么说;)我只能使用for循环或while循环来执行此操作。这很好。我已经解释了错误的原因。我认为
map
的源代码使用for循环,所以如果有人抱怨,就这么说;)