在Python 3中,解决这个问题的方法是使用all或3.7以上版本中的“内省调用”语法。以下是代码示例:
def f(*args):
print("f with args: ", args)
def g(*args):
print("g with args: ", args)
def h(*args):
if all(isinstance(arg, tuple) for arg in args):
print("h with tuple args: ", args)
else:
print("h with non-tuple args: ", args)
h((1,2), (3,4), (5,6))
# Output: h with tuple args: ((1, 2), (3, 4), (5, 6))
h((1,2), (3,4), 5, 6)
# Output: h with non-tuple args: ((1, 2), (3, 4), 5, 6)
f(*((1,2), (3,4), (5,6)))
# Output: f with args: ((1, 2), (3, 4), (5, 6))
g(*((1,2), (3,4), (5,6)))
# Output: g with args: ((1, 2), (3, 4), (5, 6)))
在上面的示例中,我们定义了三个函数(f,g和h),其中h使用了all来检查是否所有参数都是元组。然后,我们使用h分别调用包含元组的和不包含元组的参数。在调用f和g时,我们使用解包语法来传递元组参数。
下一篇:变差函数手动计算