Can Python's map function call object member functions?

后端 未结 5 1788
無奈伤痛
無奈伤痛 2021-02-01 14:31

I need to do something that is functionally equivalent to this:

for foo in foos:
    bar = foo.get_bar()
    # Do something with bar

My first i

5条回答
  •  情话喂你
    2021-02-01 14:35

    I think the cleanest way is to forgo the for-loop completely and use a list comprehension:

    bars = [foo.get_bar() for foo in foos]
    

    This answer is close to some other answers but differs in that the list is actually returned and not used in the subsequent loop. Depending on what you do with bars, you may be able to use a list comprehension there to.

    I don't think the map function with lambdas are particulary readable, besides the overhead for map is considerable.

提交回复
热议问题