首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何验证传递给函数的嵌套元组的长度?

问如何验证传递给函数的嵌套元组的长度?
EN

Stack Overflow用户
提问于 2018-01-08 19:12:54
回答 3查看 764关注 0票数 1

我正在构建一个接受元组列表的函数。例如:

代码语言:javascript
复制
my_list = [
     ("str1", 1, 11),
     ("str2", 2, 22), 
     ("str3", 3, 33),
     ("str4", 4, 44)
] 

我希望创建一个具有定义的函数,以便它只接受每个嵌套元素大小为"3“的参数。如何定义函数仅接受所需嵌套长度的列表?

下面是我试图实现的目标的示例代码片段(我知道这在语法上是不正确的)

代码语言:javascript
复制
def newattr_ratio(data, *(name,idx,idy)):

    for name,idx,idy in *(name,idx,idy):
        data[name]= data[data.columns[idx]]/data[data[columns[idy]]]

如何使用这样的参数定义创建函数?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-01-08 19:23:05

您不能在函数参数声明期间限制这一点。但是,您可以创建一个自定义装饰器,以检查嵌套元组的长度,如:

代码语言:javascript
复制
from functools import wraps

def check_params(nestedsize=None):
    def _check_params(func):
        def _decorator(data, *args ):
            if nestedsize and all(len(arg)==nestedsize for arg in args):
                return func(data, *args)
            else:
                raise Exception("Invalid args passed with the function call")
        return wraps(func)(_decorator)
    return _check_params

上面的装饰器使用可选的参数nestedsize来检查嵌套元组的大小。

现在,为了将列表的解压缩版本传递给函数,您的函数定义应该是:

代码语言:javascript
复制
@check_params(nestedsize=3)    # <-- added decorator here, with nested size as "3"
def newattr_ratio(data, *args):  # <-- note the asterisk sign here
    for name, idx, idy in args:
        print("{} - {} - {}".format(name, idx, idy))

样本运行:

代码语言:javascript
复制
# Correct input
>>> my_list = [("a", 1, 11), ("b", 2, 22), ("c", 3, 33)]

#                     v asterisk again to unpack the list
>>> newattr_ratio([], *my_list)
a - 1 - 11
b - 2 - 22
c - 3 - 33

# Incorrect input, raising custom exception
>>> my_list = [("a", 1, 11, "wrong_data"), ("b", 2, 22), ("c", 3, 33)]

>>> newattr_ratio([], *my_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in _decorator
Exception: Invalid args passed with the function call

如果不想解压缩列表并将其作为传递,那么您的函数应该是:

代码语言:javascript
复制
@check_params(nestedsize=3) 
def newattr_ratio(data, args):  # <-- No asterisk here
    for name, idx, idy in args:
        print("{} - {} - {}".format(name, idx, idy))
        # ... whatever your logic is

示例运行(结果与上面相同,只是函数调用不同)

代码语言:javascript
复制
# correct input
>>> my_list = [("a", 1, 11), ("b", 2, 22), ("c", 3, 33)]
>>> newattr_ratio([], my_list)   # <-- No asterisk here
a - 1 - 11
b - 2 - 22
c - 3 - 33

# Incorrect input, raising custom exception
>>> my_list = [("a", 1, 11, "wrong_data"), ("b", 2, 22), ("c", 3, 33)]

>>> newattr_ratio([], my_list)   # <-- No asterisk here
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in _decorator
Exception: Invalid args passed with the function call

但是,如果您不使用装饰符,那么不管怎么说,for循环都会将异常引发为ValueError: too many values to unpack。因此,如果您没有自定义异常,则可以跳过装饰器。

例如:

代码语言:javascript
复制
#                               v extra value here
>>> my_list = [("a", 1, 11, "wrong_data"), ("b", 2, 22), ("c", 3, 33)]

>>> newattr_ratio([], my_list)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in newattr_ratio
ValueError: too many values to unpack
票数 1
EN

Stack Overflow用户

发布于 2018-01-08 19:23:43

你搞错了。处理可变参数量的格式是"def newattr_ratio(data,*t_uple)“。"*t_uple“表示它将是可变的参数数量。下面是一个例子:

代码语言:javascript
复制
def add (*arg):
    sum = 0
    for t_uple in arg:
        for x in t_uple:
            sum = sum +x
    return sum

if __name__ == '__main__':
    arg_1 = (1, 2, 3)
    arg_2 = (5, 6, 7)
sum = add(arg_1,arg_2)
print(sum)
票数 0
EN

Stack Overflow用户

发布于 2018-01-08 19:14:17

函数接受元组列表作为参数

代码语言:javascript
复制
def newattr_ratio(data, myListOfTuples):
    for myTuple in myListOfTuples:
        data[myTuple[0]]= data[data.columns[myTuple[1]]/data[data[columns[myTuple[2]]]
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48156691

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档