【问题标题】:Function with arguments in two lists具有两个列表中的参数的函数
【发布时间】:2012-02-29 08:49:03
【问题描述】:

我有两个列表 xscat 和 yscat。我希望列表理解分别在 xscat 和 yscat 中提取 x 和 y。结果列表应包含 peaks([x[0], y[0]]), peaks([x[1], y[1]])

xscat=yscat=[-1, -1.5,5]
[peaks([x,y]) for x,y in xscat,yscat]

你能找到任何使用推导的解决方案吗?或其他方式放置它(地图)?

【问题讨论】:

    标签: python dictionary list-comprehension


    【解决方案1】:

    zip 是你想要的:

    [peaks([x,y]) for x,y in zip(xscat,yscat)]
    

    【讨论】:

      【解决方案2】:

      你需要使用zip:

      [peaks([x,y]) for (x,y) in zip(xscat, yscat)]
      

      【讨论】:

        【解决方案3】:

        试试 zip:http://docs.python.org/library/functions.html#zip

        [peaks(x) for x in zip(zscat, yscat)]
        

        编辑

        这假设峰可以接受一个元组。

        【讨论】:

          【解决方案4】:

          我从您的示例中假设您想使用 zip() 但是,以防万一您真正想要做的是迭代 xscat 和 yscat 的所有可能组合,那么您还有更多工作要做...

          所以,如果你想要 (xscat[0],yscat[0]), (xscat[0], yscat[1]), (xscat[0], yscat[2]) 等等...你可以首先做一个嵌套理解:

          ((x,y) for x in xscat for y in yscat)

          将生成所有对和

          [peaks(x,y) for x in xscat for y in yscat]

          如果您想要所有排列,应该产生解决方案。

          另外,请注意 zip/map - 如果列表(xscat 和 yscat)的长度不同,您将获得不同的结果 - 请确保选择能够产生所需解决方案的列表。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2020-07-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多