Simpler way to create dictionary of separate variables?

前端 未结 27 1892
名媛妹妹
名媛妹妹 2020-11-22 02:42

I would like to be able to get the name of a variable as a string but I don\'t know if Python has that much introspection capabilities. Something like:

>&         


        
27条回答
  •  既然无缘
    2020-11-22 03:14

    As unwind said, this isn't really something you do in Python - variables are actually name mappings to objects.

    However, here's one way to try and do it:

     >>> a = 1
     >>> for k, v in list(locals().iteritems()):
             if v is a:
                 a_as_str = k
     >>> a_as_str
     a
     >>> type(a_as_str)
     'str'
    

提交回复
热议问题