【问题标题】:Python 3 : Two or more tuples as argumentsPython 3:两个或多个元组作为参数
【发布时间】:2021-04-17 15:21:11
【问题描述】:

是否可以在 Python 3 中解压缩两个元组作为函数的参数?

代码是这样的......

def fun(*tuple1, *tuple2):
    #some code to compare elements of tuple1 to elements of tuple2

谢谢!

【问题讨论】:

  • 如果你可以这样做,你将如何决定 fun(1, 2, 3, 4, 5) 中的哪些参数到哪个元组?
  • 你可能会想到 Python 2 允许的东西:def fun((x0, x1), (y0, y1)): ...,之后像 fun(t1, t2) 这样的调用会为你解包这两个元组。这已从 Python 3 中删除以简化函数定义,强制您在函数体中显式解包元组。
  • 如果你想比较两个元组元素,zip 是你的朋友:for x, y in zip(t1, t2): ... 让你对t1[0]t2[0] 进行操作,然后是t1[1]t2[1] ,然后是t1[2]t2[2],以此类推。 for 循环执行的分配在并行迭代两个元组时为您解包。
  • 哦!谢谢!我肯定会尝试使用 zip 功能!

标签: python python-3.x arguments tuples


【解决方案1】:

不,因为确定第一个元组的结束位置和第二个元组的开始位置会很模糊。

有两种解决方法:

你可以直接取两个元组:

def fun(tulpe1, tuple2):
    # compare tuple1 to tuple2

或者,您可以将多个元组作为 kwargs:

def fun(**tuples):
    # for tuple in tuples:
    #     do some stuff

【讨论】:

    猜你喜欢
    • 2022-11-01
    • 1970-01-01
    • 2019-10-31
    • 2021-06-01
    • 2021-09-21
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2015-07-31
    相关资源
    最近更新 更多