简体   繁体   English

Python 打印列表内的变量名称

[英]Python printing variable name that is inside of a list

Hello I was wondering how I would print the variable names inside of my list.您好,我想知道如何在列表中打印变量名。 Thanks谢谢

traits = [Character, Eye, Hair, Mouth, Shirt]
attributes.append({'trait_type': f"{traits=}", 'value': (os.path.basename(traits[a]))[:-4]})

What I want the output to be is:我想要的 output 是:

'trait_type': 'Character'

I was searching and alot of threads said to make a dictionary, but wasn't sure if there was a way to brute force it.我正在搜索并且很多线程都说要制作字典,但不确定是否有办法强制它。 Thanks.谢谢。

Replace the code to be the following将代码替换为以下

mydict = {
    'var1-name': 'var1-value',
    'var2-name': 'var2-value',
    'var3-name': 'var3-value'
}

for name in mydict:
    print(name, mydict[name])

Why?为什么?

To be honest, because you cannot print an variable name inside a list,老实说,因为你不能在列表中打印变量名,

you can check here --> How to print variable name in a list你可以在这里查看 -->如何在列表中打印变量名


Solution解决方案

We need to change the list to become a dictionary to be able to print variable name in Python.我们需要将列表更改为字典,以便能够在 Python 中打印变量名称。

one way of doing this:一种方法:

first = 'green'
second = 'yellow'
third = 'orange'
mycolors = ['first','second','third']
for each in mycolors:
    print(each, vars()[each])

Output Output

first green
second yellow
third orange

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

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