【问题标题】:passing multiple arguments in python on a loop在循环中在python中传递多个参数
【发布时间】: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

【问题讨论】:

    标签: python arguments function-call multiple-arguments


    【解决方案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)
      

      【讨论】:

        猜你喜欢
        • 2020-04-20
        • 1970-01-01
        • 2018-09-21
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-05-19
        相关资源
        最近更新 更多