如何在 Python 中将列表扩展为函数参数 [英] How to expand a list to function arguments in Python

查看:26
本文介绍了如何在 Python 中将列表扩展为函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有语法允许您将列表扩展为函数调用的参数?

Is there syntax that allows you to expand a list into the arguments of a function call?

示例:

# Trivial example function, not meant to do anything useful.
def foo(x,y,z):
   return "%d, %d, %d" %(x,y,z)

# List of values that I want to pass into foo.
values = [1,2,3]

# I want to do something like this, and get the result "1, 2, 3":
foo( values.howDoYouExpandMe() )

推荐答案

它存在,但很难搜索.我想大多数人都称它为splat"运算符.

It exists, but it's hard to search for. I think most people call it the "splat" operator.

它在文档中作为解压参数列表".

你会像这样使用它:foo(*values).还有一个用于字典:

You'd use it like this: foo(*values). There's also one for dictionaries:

d = {'a': 1, 'b': 2}
def foo(a, b):
    pass
foo(**d)

这篇关于如何在 Python 中将列表扩展为函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆