【问题标题】:Python (3.8) : map(lambda x: x.method() , list_of_objects) not working on [duplicate]Python(3.8):map(lambda x:x.method(),list_of_objects)不起作用[重复]
【发布时间】:2020-07-12 16:36:11
【问题描述】:

当我将 map lambda 应用于对象列表时,我找不到它不起作用的原因,例如:

class test():
    def __init__(self, input):
        self.input =input

    def print_intput(self):
        print(self.input)

objectlist=[]
for count in list(range(1,6)):
    objectlist.append(test(count))


for ob in objectlist:
    ob.print_intput()
"""
This ouputs:
1
2
3
4
5

"""
map(lambda x: x.print_intput(), objectlist)
"""
This has no output
"""

为什么第一个输出方法有效,简单的for循环和map(这种情况下lambda方法不起作用)。

【问题讨论】:

    标签: python class dictionary lambda python-3.8


    【解决方案1】:

    map 返回一个迭代器,当您对其进行迭代时,将对列表中的每个元素一次调用一个 lambda 并返回结果。

    将它传递给list 将消耗迭代器并为您提供输出

    list(map(lambda x: x.print_intput(), objectlist))
    

    【讨论】:

    • (由于 OP 编写了冗余模式 for i in list(range(...)): 并且这与此答案直接相关,因此您也可以扩展此答案以讨论该问题-您说什么?)
    • 供以后参考,需要注意的是,这里生成的列表将是[None, None, None, None, None],因为print_input()不返回任何内容。
    • Iain Shelvington 提出的解决方案只返回 None ,这显然不是目标。但是,在另一个使用函数而不是类的示例中添加“列表”确实有效。我发现的唯一解决方案就是使用 for 循环。仍然不确定为什么 map lambda 不起作用。
    • @Karl Knechtel 我不明白为什么我的问题被关闭了,我浏览了其他示例,将其列为列表并不是其他示例中提出的解决方案。
    猜你喜欢
    • 2015-03-09
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2015-04-30
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多