简体   繁体   English

如何在不使用 splat 运算符的情况下解压缩具有不同数量元素的元组?

[英]How do i unpack tuple with different number of elements without using splat operator?

It is a part of my university project, and I am trying to make a function that returns multiple variables (unpacked tuple) to call another function with a proper number of arguments.它是我大学项目的一部分,我正在尝试制作一个返回多个变量(解压缩的元组)的函数,以使用适当数量的参数调用另一个函数。

value = function_list[i](*func())

This was easy just using *(splat) operator until one of our instructors told us not to use this operator.这很容易使用 *(splat) 运算符,直到我们的一位讲师告诉我们不要使用此运算符。 Then, I tried to unpack tuple by assigning it into variables manually.然后,我尝试通过手动将元组分配给变量来解压缩元组。

a, b = func()
function_list[i](a, b) #Causes error when a function requires more/less than 2 arguments.

Function_list is a list of multiple function definitions that may have a different number of parameters. Function_list 是多个函数定义的列表,这些函数定义可能具有不同数量的参数。 So this is a problem in some cases.所以在某些情况下这是一个问题。 Those functions are not made by myself therefore I can't change those parameters to be optional.这些功能不是我自己制作的,因此我无法将这些参数更改为可选。

Is there any finest way to replace * operator to get my all functions working properly?有没有最好的方法来替换 * 运算符以使我的所有功能正常工作?

Also, I am not allowed to use these keywords:另外,我不允许使用这些关键字:

as, assert, asynch, await, break, class, continue, except, finally, global, is, lambda, nonlocal, raise, try, with, yield. 

I think it is a weird requirement not to be able to use * , but here's what I've come up with:我认为不能使用*是一个奇怪的要求,但这是我想出的:

import inspect, functools

def get_min_max_arg_count(func):
    params = inspect.signature(func).parameters
    defaults = [p.default for p in params.values()]
    return defaults.count(inspect._empty), len(params)

def call_with_params(func, params):
    for param in params:
        func = functools.partial(func, param)
    return func()

def call_matching_func(func, function_list):
    '''Call `func` and the first function in `function_list` that
       has a signature matching the tuple returned by `func`.'''
    params = func()
    n_params = len(params)
    for fn in function_list:
        n_req, n_max = get_min_max_arg_count(fn)
        if n_req <= n_params <= n_max:
            return call_with_params(fn, params)

Note that call_matching_func assumes that any func you'll pass in returns an iterable.请注意, call_matching_func假定您将传入的任何func都返回一个可迭代对象。

Note also that I've decided that keyword arguments do not exist.另请注意,我已决定不存在关键字参数。

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

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