【问题标题】:Passing arguments in function dynamically in Python 3在 Python 3 中动态地在函数中传递参数
【发布时间】:2016-02-16 08:53:56
【问题描述】:

当我调用函数时,python 是否支持动态参数传递?

  import itertools.product
  l = [1,2,3,95,5]
  for i in range(5):
      for n in itertools.product(l,l):
         #calculations that
         #reduce set size

我希望通过 i 产品的迭代:

i=1: 产品(l,l)

i=2: 产品(l,l,l)

i=3: 产品(l,l,l,l)

...

如果我没记错的话,我所知道的唯一支持这种功能的语言是 PHP。

【问题讨论】:

    标签: python python-3.x arguments parameter-passing


    【解决方案1】:

    itertools.product 接受可选的关键字参数repeat

    所以,你可以这样做:

    for n in itertools.product(l, repeat=i+1):
        ...
    

    或者,要动态传递参数,您可以使用*args(参见Unpacking argument lists):

    for n in itertools.product(*([l] * (i+1))):
        ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-02
      • 2018-11-12
      • 1970-01-01
      • 2012-07-30
      • 2017-12-26
      • 1970-01-01
      • 2013-05-08
      • 2015-11-14
      相关资源
      最近更新 更多