【问题标题】:How to pass items as args lists in map?如何在地图中将项目作为参数列表传递?
【发布时间】:2010-12-23 22:38:00
【问题描述】:

这是我的一段代码。 Lambda 接受 3 个参数,我想将它们作为位置参数的元组传递,但显然 map 将它们作为单个参数提供。

如何将底部的元组作为参数列表提供? (我知道我可以重写 lambda,但它会变得不太可读)

 adds = map((lambda j, f, a:
      j.join([f.format(i) for i in parse.options[a]]) if parse.options[a] else ''),
      ((' ', ' -not -path "{0}" ', 'exclude'),
      (' -or ', '-path "{0}"', 'include')))

【问题讨论】:

    标签: python map arguments


    【解决方案1】:

    尝试在它们周围放上括号

    adds = map((lambda (j, f, a):
      j.join([f.format(i) for i in parse.options[a]]) if parse.options[a] else ''),
      ((' ', ' -not -path "{0}" ', 'exclude'),
      (' -or ', '-path "{0}"', 'include')))
    

    【讨论】:

    • 太棒了!不敢相信这么简单!
    • 请注意,这种方法在 Python > 3.0 中无效,不再支持这种类型的参数解构。一个函数 f(a, (b, c): return a+b+c 需要写成 f(a, b_c): b, c = b_c return a+b+c 问候,Rickard
    【解决方案2】:

    一种方法是重写为列表推导:

    adds = [
      j.join([f.format(i) for i in parse.options[a]]) if parse.options[a] else ''
      for j, f, a in
      ((' ', ' -not -path "{0}" ', 'exclude'),
      (' -or ', '-path "{0}"', 'include'))]
    

    【讨论】:

      【解决方案3】:

      map() 描述:

      map(function, iterable, ...)

      将函数应用于可迭代的每个项目并返回结果列表。 如果传递了额外的可迭代参数,则函数必须接受那么多参数并并行应用于所有可迭代项中的项目。如果一个可迭代对象比另一个更短,则假定使用 None 项进行扩展。如果 function 为 None,则假定恒等函数;如果有多个参数,则 map() 返回一个由元组组成的列表,其中包含来自所有可迭代对象的相应项(一种转置操作)。可迭代参数可以是序列或任何可迭代对象;结果总是一个列表。

      您需要将参数放在并行列表或元组中,并将它们作为 3 个可迭代对象传递给 map()

      【讨论】:

      • 是的,这是正确的,但代码(元组)将不可读。
      【解决方案4】:

      另一种方法是使用接受预压缩参数的 itertools.starmap:

      adds = itertools.starmap((lambda j, f, a:
          j.join([f.format(i) for i in parse.options[a]]) if parse.options[a] else ''),
          ((' ', ' -not -path "{0}" ', 'exclude'),
          (' -or ', '-path "{0}"', 'include')))
      

      【讨论】:

        猜你喜欢
        • 2010-11-30
        • 1970-01-01
        • 2017-05-20
        • 2013-11-10
        • 2020-11-06
        • 2013-04-21
        • 1970-01-01
        • 2014-12-03
        • 1970-01-01
        相关资源
        最近更新 更多