【问题标题】:TypeError: 'int' object is not iterable. Python error when using map() inside a functionTypeError:'int' 对象不可迭代。在函数中使用 map() 时出现 Python 错误
【发布时间】:2020-06-25 10:21:45
【问题描述】:

我正在尝试学习在列表中添加相应元素的不同方法。 目前卡在这里,当我不使用函数时,代码很有趣。 协助?

from operator import add
#Setting up the lists
matrix_a = [23,1,4,8]
matrix_b = [3,11,3,2]

def add(in_list1,in_list2):
   final_list = list(map(add, in_list1, in_list2))

   return final_list

matrix_c = add(matrix_a,matrix_b)
print(matrix_c)

【问题讨论】:

    标签: python dictionary iterable


    【解决方案1】:

    这里有两个add 函数,一个是从运算符导入的,一个是您自己创建的,将您的def add 更改为其他值,例如def add2,并适当地更改函数调用。

    【讨论】:

      【解决方案2】:

      将您的函数命名为 add 以外的名称。你已经覆盖了从operator 导入的名称add,所以list(map(add, in_list1, in_list2)) 中的add 指的是你自己的函数。

      【讨论】:

        【解决方案3】:

        更改函数名称和创建列表:

        matrix_a = [23,1,4,8]
        matrix_b = [3,11,3,2]
        
        def sum(in_list1,in_list2):
            return[*map(lambda x, y: x +y, in_list1, in_list2)]
        
        print(sum(matrix_a,matrix_b))
        

        【讨论】:

        • OP的问题是名称冲突,你建议使用内置名称?
        猜你喜欢
        • 1970-01-01
        • 2020-06-10
        • 2015-04-06
        • 2013-10-31
        • 1970-01-01
        • 2018-08-03
        • 2018-08-17
        • 2020-11-28
        相关资源
        最近更新 更多