简体   繁体   English

TypeError:“ int”对象不可迭代“我在做什么错? ”

[英]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.

相关问题 为什么我收到Typeerror:“ int”对象不可迭代 - Why am I getting Typeerror: 'int' object not iterable 为什么我收到TypeError:“ int”对象在我的代码中无法迭代? - Why am I getting TypeError: 'int' object is not iterable in my code? 为什么我收到 TypeError: 'int' object is not iterable? - Why am I getting TypeError: 'int' object is not iterable? 进行多处理时出现“TypeError: 'type' object is not subscriptable”。 我究竟做错了什么? - "TypeError: 'type' object is not subscriptable" when doing multiprocessing. What am I doing wrong? 我究竟做错了什么? “类型错误:不能将序列乘以‘str’类型的非整数” - What am I doing wrong? "TypeError: can't multiply sequence by non-int of type 'str'" 'TypeError:str object 不能解释为整数'我做错了什么? - 'TypeError: str object cannot be interpreted as an integer' What am I doing wrong? 我一直在 Python 上收到错误消息,TypeError: unsupported operand type(s) for /: 'tuple' and 'int' 我做错了什么? - I keep getting an error on Python, TypeError: unsupported operand type(s) for /: 'tuple' and 'int' What am I doing wrong? 基本程序TypeError。 我究竟做错了什么? - Rudimentary program TypeError. What am I doing wrong? 类型错误:Int 对象不可迭代 - TypeError: Int object is not iterable 类型错误:“int”对象不可迭代? - TypeError: 'int' object is not iterable?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM