【问题标题】:Return different value depending on number of arguments in a function [duplicate]根据函数中的参数数量返回不同的值[重复]
【发布时间】:2018-07-06 14:05:44
【问题描述】:

我正在尝试创建一个函数,该函数接受 1 到 5 个参数,并根据给定的数字进行不同的计算。 我的想法是这样的:

def function(*args)
    num_of_args = (!!here is the problem!!)
if(num_of_args == 1) : result = a
else if(number_of_args == 2) : result = a+b

等等 我试图计算参数的数量并将该数字分配给变量但找不到方法 我想可能没有必要使用 5 个 if,但我真的不想在计算这些参数之前专注于它

【问题讨论】:

  • 可以使用len(args)获取传递的参数个数

标签: python python-3.x


【解决方案1】:

您可以使用len(args)

def function(*args):
    if len(args) == 0:
        print("Number of args = 0")
    elif len(args) == 1:
        print("Number of args = 1")
    else:
        print("Number of args >= 2")

【讨论】:

  • 谢谢!我会接受这个
【解决方案2】:

使用*args,位置参数作为列表发送。您可以使用 args[0],args[1].... 也可以通过 len(args) 访问它们

def foo(*args):
  print(len(args))

【讨论】:

  • 谢谢,不知道!
猜你喜欢
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多