【问题标题】:python map function passing multiple parameterspython map函数传递多个参数
【发布时间】:2013-07-13 14:48:02
【问题描述】:

首先我需要在 python 中使用 map 函数而不是理解来实现多处理

我的列表理解的初始版本如下

t3List = [x for x in rowCost if ( cost[t1][t2]+cost[rowCost.index(x)][tour[ tour.index(rowCost.index(x)) - 1 ] ]-cost[t2][rowCost.index(x)]-cost[t1][tour[ tour.index(rowCost.index(x)) - 1 ] ]>0 and rowCost.index(x) !=t1 and rowCost.index(x) != t2 and rowCost.index(x) != tour[ tour.index(t2)+1]  and x<cost[t1][t2] ) ]

为了更好地理解t1t2 只是顶点。例如t1,t2 的值分别为 34,21。 rowcost 是一个列表,其中包含从一个顶点到其他每个顶点的距离。

tour 只是我必须旅行的一些顶点顺序(基本上我正在解决 tsp)

这里所有的变量都是局部的。 cost 就像一个所有顶点的对称成本矩阵。

对于大量顶点,此列表需要 0.5 到 1 秒来计算。所以看了this之后打算实现多处理

我知道 map 函数将第一个参数作为函数。

但是要实现上述理解,这个函数必须有多个参数,因为所有变量都是局部的。

如何解决这个问题?非常感谢任何帮助。

【问题讨论】:

    标签: list python-2.7 map multiprocessing list-comprehension


    【解决方案1】:

    试试这个代码:

    def f(rowCost, x, cost, t1, t2, tour):
        if cost[t1][t2]+cost[rowCost.index(x)][tour[ tour.index(rowCost.index(x)) - 1 ] ]-cost[t2][rowCost.index(x)]-cost[t1][tour[ tour.index(rowCost.index(x)) - 1 ] ]>0 and rowCost.index(x) !=t1 and rowCost.index(x) != t2 and rowCost.index(x) != tour[ tour.index(t2)+1]  and x<cost[t1][t2]:
            return x
        else:
            return None
    
    t3List = filter(None, map(f, rowCost))
    

    我假设rowCost 的任何值都不能为None 赋值,以便用filter 减少map 结果

    【讨论】:

    • 我不相信这会起作用,因为函数 f 需要多个参数,而 map 调用只给它 rowCost 可以使用。
    • 上述解决方案给了我一个错误,是完全错误的。我在我的问题中也提到了这一点,即 f 是一个只接受一个参数的函数,即 x
    【解决方案2】:

    我认为你想要的是 jabaldonedo 的答案,除了函数 f 接受 x, cost, t1, t2, tour 之外,这些值应该在其他地方定义,它应该只引用它们。即你的函数应该从一个有多个参数的函数“curried”成一个只有一个参数的函数。

    def f(rowCost):
        if <huge boolean expression>:
            return x
        else:
            return None
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-19
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 2013-06-28
      • 1970-01-01
      相关资源
      最近更新 更多