简体   繁体   English

如何从 python 中的 *args 打印变量名

[英]how to print variable name from *args in python

I have defined a function taking a variable number of arguments.我已经定义了一个 function,它采用可变数量的 arguments。

These arguments will all be lists of floats, each variable having a name, say a , b , c , for 3 arguments.这些 arguments 都将是浮点数列表,每个变量都有一个名称,例如abc ,用于 3 个 arguments。 They will look like:它们看起来像:

a=[1,2]
b=[3,4]
c=[5,6]

I want to be able to work with the name of these arguments, ie我希望能够使用这些 arguments 的名称,即

def function(*args):
    for arg in args:
        plt.plot(x_value, arg, label="the name of arg")

I call the function as function(a,b,c)我将 function 称为function(a,b,c)

"the name of arg" shall be the string a for the first iteration of the for loop, the string b for the second iteration of the for loop and the string c for the third iteration of the for loop. "the name of arg"应该是 for 循环的第一次迭代的字符串a ,for 循环的第二次迭代的字符串b和 for 循环的第三次迭代的字符串c

What shall I put there at label= ?我应该在label=处放什么? I have tried various approaches, they all result either in printing the string arg , or the actual value of arg , ie [1,2] for the first iteration of the for-loop.我尝试了各种方法,它们都导致打印字符串argarg的实际值,即 for 循环的第一次迭代的 [1,2] 。

Thank you!谢谢!

If you want the argument names, you have to use named arguments or a dictionary.如果您想要参数名称,则必须使用命名 arguments 或字典。

def function(**kwargs):
    for name, value in kwargs.items():
        plt.plot(x_value, value, label=name)

function(a=a, b=b, c=c)

This passes three named arguments to the function, a , b , and c .这会将三个名为 arguments 的文件传递给 function、 abc

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

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