简体   繁体   中英

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

The problem is, that the function avg() is expecting 3 lists from the map() . But map() doesn't function that way and instead it provides one element from each iterable, which is 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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