在循环中在python中传递多个参数

时间:2019-02-03 22:00:53

标签: python arguments function-call multiple-arguments

我有一个函数,该函数接受元组的多个参数并进行相应的处理。我想知道是否可以在for循环中传递参数。 例如:

def func(*args):
   for a in args:
      print(f'first {a[0]} then {a[1]} last {a[2]}')

然后我将该函数称为

func(('is', 'this', 'idk'), (1,2,3), ('a', '3', 2))

我的问题是我是否可以在不更改函数定义本身的情况下修改循环调用的函数:

func((i, i, i) for i in 'yes'))

将其打印:

first y then y last y
first e then e last e
first s then s last s

1 个答案:

答案 0 :(得分:1)

是的,通话中有generator expression* argument unpacking

func(*((i, i, i) for i in 'yes'))

也可以先将生成器表达式分配给变量来编写:

args = ((i, i, i) for i in 'yes')
func(*args)

演示:

>>> func(*((i, i, i) for i in 'yes'))
first y then y last y
first e then e last e
first s then s last s
>>> args = ((i, i, i) for i in 'yes')
>>> func(*args)
first y then y last y
first e then e last e
first s then s last s