Simpler way to create dictionary of separate variables?

前端 未结 27 1894
名媛妹妹
名媛妹妹 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:13

    I've wanted to do this quite a lot. This hack is very similar to rlotun's suggestion, but it's a one-liner, which is important to me:

    blah = 1
    blah_name = [ k for k,v in locals().iteritems() if v is blah][0]
    

    Python 3+

    blah = 1
    blah_name = [ k for k,v in locals().items() if v is blah][0]
    

提交回复
热议问题