Python:使用函数

时间:2016-03-17 18:07:06

标签: python tuples unpack

我的代码是这样的:

def f1():
    return 2, 3

def f2():
    return 1, f1()

我能做到:

a, (b, c) = f2()

我想这样做:

a, b, c = f2()

我能找到的所有解决方案都需要使用大量疯狂的括号/括号,或创建一个身份函数来使用*运算符。我想只修改f2()。

有什么更简单的东西吗?

1 个答案:

答案 0 :(得分:8)

不使用/// <summary> /// Specifies a function that will calculate the value to return from the method, /// retrieving the arguments for the invocation. /// </summary> /// <typeparam name="T1">The type of the first argument of the invoked method.</typeparam> /// <typeparam name="T2">The type of the second argument of the invoked method.</typeparam> /// <param name="valueFunction">The function that will calculate the return value.</param> /// <return>Returns a calculated value which is evaluated lazily at the time of the invocation.</return> /// <example> /// <para> /// The return value is calculated from the value of the actual method invocation arguments. /// Notice how the arguments are retrieved by simply declaring them as part of the lambda /// expression: /// </para> /// <code> /// mock.Setup(x => x.Execute( /// It.IsAny<int>(), /// It.IsAny<int>())) /// .Returns((int arg1, int arg2) => arg1 + arg2); //I fixed that line, it's different in the documentation and is incorrect /// </code> /// </example> IReturnsResult<TMock> Returns<T1, T2>(Func<T1, T2, TResult> valueFunction); ,而是使用元组连接:

1, f2()

如评论中所述,您也可以这样做:

def f2():
    return (1,) + f1()

你也可以这样做:

def f2():
    x,y = f1()
    return 1, x, y

这有点长,但它优于def f2(): return (lambda *args: args)(1, *f1()) 解决方案,因为这种方式x,y = f1()可以返回包含任意数量元素的元组。