简体   繁体   English

Python:函数参数作为具有单个输出的元组

[英]Python: function parameters as a tuple with single output

I have a function in Python which calculates the entropy of a number of parameters which I call ps as follows 我在Python中有一个函数,它计算了许多参数的熵,我称之为ps ,如下所示

def H(*ps): 
    sum = 0.0
    for pi in ps:
        sum = sum - pi*np.log2(pi)
    return sum

I want to be able to pass in multiple parameters as a list or tuple, ie H([x]) but this doesn't give the correct result, rather it calculates the value of H(xi) and returns a tuple with each result. 我希望能够将多个参数作为列表或元组传递,即H([x])但这不会给出正确的结果,而是计算H(xi)的值并返回每个结果的元组。 I am able to sum each element of the tuple to get the correct result due to the nature of the function but I'd rather be able to have the function give the desired output for convenience. 由于函数的性质,我能够对元组的每个元素求和以获得正确的结果,但我宁愿能够为函数提供所需的输出以方便起见。 If I enter H(x1, x2, ...) the function gives the correct output. 如果我输入H(x1, x2, ...) ,函数会给出正确的输出。

If anyone has any suggestions please let me know. 如果有人有任何建议,请告诉我。

Thanks in advance. 提前致谢。

EDIT: 编辑:

Sample input and output: 样本输入和输出:

x = [0.1, 0.2]
print H(0.1, 0.2), H(x)

0.796578428466 [ 0.33219281  0.46438562]

Don't unpack via the * operator in your function definition. 不要在函数定义中通过*运算符解压缩。 You are already iterating your list via your for loop. 您已经通过for循环迭代列表for It's natural to use an iterable as a function argument. 使用iterable作为函数参数是很自然的。

def H(ps): 
    x = 0.0
    for pi in ps:
        x = x - pi*np.log2(pi)
    return x

res = H([0.1, 0.2])

print(res)
0.796578428466

In addition, don't shadow the built-in sum , this is poor practice. 另外,不要影子内置sum ,这是不好的做法。

You can pass the argument as a list or tuple . 您可以将参数作为listtuple传递。 You can avoid using unpack trick here. 你可以避免在这里使用unpack技巧。

def H(ps): #updated, not asterisk 
    my_sum = 0.0
    for pi in ps:
        my_sum = my_sum - pi*np.log2(pi)
    return my_sum
x = [0.1, 0.2]
print (H([0.1, 0.2])) #argument as list
print(H(x)) #argument as list

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

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