【问题标题】:Function Argument Packing And Unpacking Python函数参数打包和解包 Python
【发布时间】:2019-04-14 18:21:21
【问题描述】:

目前,我有这样的功能:

def my_func(*args):
    #prints amount of arguments
    print(len(args))
    #prints each argument
    for arg in args:
        print(arg)

我想将多个参数传递给这个函数,但以下对我不起作用。它在 else 之后的星号 * 上给出了语法错误。

my_func(
    *(1, 2, 3, 4)
    if someBool is True
    else *(1, 2)
)

我发现的解决方法是先放入 1 和 2,然后在检查 someBool 时放入 3 和 4。

my_func(
    1, 2,
    3 if someBool is True else None,
    4 if someBool is True else None
)

我对上述情况很好,因为我的函数检查无,但如果有替代方案,我很乐意感谢他们。

【问题讨论】:

  • 为什么不在函数调用之外写if语句?
  • 我有一个函数接受 2、4 或任何偶数个参数。把它放在一个函数中使它(对我来说)更容易检查和理解。我会把它放在外面,但我更喜欢三元运算符。感谢您的建议:D

标签: python python-3.x function ternary-operator


【解决方案1】:

*移到... if ... else ...之外:

my_func(
    *((1, 2, 3, 4)
      if someBool is True
      else (1, 2))
)

【讨论】:

    【解决方案2】:

    您需要一组额外的括号。此外,您不需要说 is True 来检查布尔值在 python 中是否“真实”,使其成为:my_func(*((1, 2, 3, 4) if someBool else (1, 2)))

    【讨论】:

    • is True 被包括在内,因为我想防止一些可能的混淆。下次我会省略它:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-28
    • 2020-07-17
    • 1970-01-01
    • 2021-09-22
    相关资源
    最近更新 更多