[英]TypeError: 'int' object is not iterable “ What am I doing wrong? ”
A simple program to calculate average of elements of same indices of given number of lists and print the result. 一个简单的程序,可以计算给定数量的列表的相同索引的元素的平均值,并打印结果。 For example, if -
例如,如果-
def avg(L1, L2, L3):
res = []
for i in L1:
for j in L2:
for k in L3:
res.append((i+j+k)/3)
break
L1 = [1, 7, 9]
L2 = [2, 3, 8]
L3 = [4, 5, 10]
for elt in map(avg, L1, L2, L3):
print(elt)
Output: TypeError: 'int' object is not iterable 输出:TypeError:'int'对象不可迭代
The problem is, that the function avg()
is expecting 3 lists from the map()
. 问题在于,函数
avg()
期望从map()
3个列表。 But map()
doesn't function that way and instead it provides one element from each iterable, which is int
. 但是
map()
不能那样工作,而是从每个可迭代对象中提供一个元素,即int
。 You can try this code: 您可以尝试以下代码:
def avg(*items):
return sum(items) / len(items)
L1 = [1, 7, 9]
L2 = [2, 3, 8]
L3 = [4, 5, 10]
for elt in map(avg, L1, L2, L3):
print(elt)
Prints: 打印:
2.3333333333333335
5.0
9.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.