简体   繁体   English

使用元组作为函数中的输入

[英]Using tuples as inputs in functions

Suppose I define a function like so, where args should be a tuple that contains two elements, an example would be (1,2) : 假设我定义了一个这样的函数,其中args应该是一个包含两个元素的元组,一个例子是(1,2)

def func(some_matrix,*args):
        return some_multiplication = some_matrix[0,first element of args] * some_matrix[0,second element of args]

How do I access the first and second elements of the tuple passed by the user in the body of the function? 如何访问用户在函数主体中传递的元组的第一和第二个元素? I also suppose that an example of calling a function would look something like: func(A,(1,2)) ? 我还假设调用函数的示例类似于: func(A,(1,2))

You could do that using list indexing or tuple indexing in this case 您可以在这种情况下使用列表索引或元组索引

def acd(val, *vag):
    print '''Given Fixed value:\t{}
    Given Variable Tuple:\t{}
    First Var Value:\t{}
    Second Var value:\t{}
    Len of var:\t{}
    Len of first var element:\t{}
    '''.format(val, vag, vag[0][0], vag[0][1], len(vag), len(vag[0]))
acd(1, (3,4))

Output: 输出:

Given Fixed value:      1
Given Variable Tuple:   ((3, 4),)
First Var Value:        3
Second Var value:       4
Len of var:     1
Len of first var element:       2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM