简体   繁体   English

在Python 3中动态传递函数中的参数

[英]Passing arguments in function dynamically in Python 3

Does python support dynamic argument passing when I call a function ? 当我调用函数时,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 want through the iterations of i the product to be: 我希望通过产品的迭代:

i=1: product(l,l) i = 1:产品(l,l)

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

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

... ...

If I can recall correctly the only language I know that supports that kind of functionality is PHP. 如果我能够正确回忆起我所知道的唯一支持这种功能的语言就是PHP。

itertools.product accepts an optional keyword argument repeat : itertools.product接受一个可选的关键字参数repeat

So, you can do: 所以,你可以这样做:

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

Alternatively, to dynamically pass argument, you can use *args (See Unpacking argument lists ): 或者,要动态传递参数,可以使用*args (请参阅解压缩参数列表 ):

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM