我知道这很有效:
def locations(city, *other_cities):
print(city, other_cities)
Run Code Online (Sandbox Code Playgroud)
现在我需要两个变量参数列表,比如
def myfunction(type, id, *arg1, *arg2):
# do somethong
other_function(arg1)
#do something
other_function2(*arg2)
Run Code Online (Sandbox Code Playgroud)
但是Python不允许两次使用它
Thi*_*ter 11
这是不可能的,因为从该位置*arg捕获所有位置参数.所以根据定义,第二个*args2永远是空的.
一个简单的解决方案是传递两个元组:
def myfunction(type, id, args1, args2):
other_function(args1)
other_function2(args2)
Run Code Online (Sandbox Code Playgroud)
并称之为:
myfunction(type, id, (1,2,3), (4,5,6))
Run Code Online (Sandbox Code Playgroud)
如果这两个函数需要位置参数而不是单个参数,你可以像这样调用它们:
def myfunction(type, id, args1, args2):
other_function(*arg1)
other_function2(*arg2)
Run Code Online (Sandbox Code Playgroud)
这样做的好处是,在调用时可以使用任何可迭代的甚至是生成器,myfunction因为被调用的函数永远不会与传递的迭代接触.
如果您真的想使用两个变量参数列表,则需要某种分隔符.以下代码None用作分隔符:
import itertools
def myfunction(type, id, *args):
args = iter(args)
args1 = itertools.takeuntil(lambda x: x is not None, args)
args2 = itertools.dropwhile(lambda x: x is None, args)
other_function(args1)
other_function2(args2)
Run Code Online (Sandbox Code Playgroud)
它会像这样使用:
myfunction(type, id, 1,2,3, None, 4,5,6)
Run Code Online (Sandbox Code Playgroud)