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

Posted

技术标签:

【中文标题】在循环中在python中传递多个参数【英文标题】:passing multiple arguments in python on a loop 【发布时间】:2019-06-27 17:08:55 【问题描述】:

我有一个函数,它接受多个元组参数并相应地处理它。我想知道是否可以在 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】:

是的,通话中有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

【讨论】:

【参考方案2】:

机器学习领域的另一种实现如下:

for clf, title, ax in zip(models, titles, sub.flatten()):
plot_contours(ax, clf, xx, yy, cmap=plt.cm.coolwarm, alpha=0.8)
ax.scatter(X0, X1, c=y, cmap=plt.cm.coolwarm, s=20, edgecolors="k")
ax.set_xlim(xx.min(), xx.max())
ax.set_ylim(yy.min(), yy.max())
ax.set_xlabel("Sepal length")
ax.set_ylabel("Sepal width")
ax.set_xticks(())
ax.set_yticks(())
ax.set_title(title)

【讨论】:

以上是关于在循环中在python中传递多个参数的主要内容,如果未能解决你的问题,请参考以下文章