Multi-arguments python map

问题描述 投票:0回答:1

我有这种情况:我有一个方法some_method(x,y)带有两个参数。第一个参数是列表temp_list,而第二个参数是字典list_of_dict的列表。

我有以下内容:

  def outer_method(self, list_of_dict):
    temp_list = []
    for x in list_of_dict:
      self.some_method(temp_list, x)
    return temp_list

但是我想知道如何使用python的map函数使代码看起来更加精致。

python python-3.x itertools
1个回答
2
投票

由于some_method通过副作用起作用(即,它使输入temp_list发生突变),因此您不应为此使用map;您的for循环是编写此代码的明智方法。 map不应用于副作用,使用高阶函数并不自动意味着您的代码会更好。

也就是说,如果some_method通过在temp_list上附加一些元素而没有改变其余内容,则可以重构,以便some_method产生这些元素而不是附加它们。然后outer_method可以像这样实现:

    def outer_method(self, list_of_dict):
        return list(chain.from_iterable(map(self.some_method, list_of_dict)))

some_method以单个字典作为参数,并且chainchain模块导入。

© www.soinside.com 2019 - 2024. All rights reserved.