Simpler way to create dictionary of separate variables?

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

    I think my problem will help illustrate why this question is useful, and it may give a bit more insight into how to answer it. I wrote a small function to do a quick inline head check on various variables in my code. Basically, it lists the variable name, data type, size, and other attributes, so I can quickly catch any mistakes I've made. The code is simple:

    def details(val):
      vn = val.__name__                 #  If such a thing existed
      vs = str(val)
      print("The Value of "+ str(vn) + " is " + vs)
      print("The data type of " + vn + " is " + str(type(val)))
    

    So if you have some complicated dictionary / list / tuple situation, it would be quite helpful to have the interpreter return the variable name you assigned. For instance, here is a weird dictionary:

    m = 'abracadabra'
    mm=[]    
    for n in m:
      mm.append(n)
    mydic = {'first':(0,1,2,3,4,5,6),'second':mm,'third':np.arange(0.,10)}
    
    
    
    details(mydic)
    
    The Value of mydic is {'second': ['a', 'b', 'r', 'a', 'c', 'a', 'd', 'a', 'b', 'r', 'a'], 'third': array([ 0.,  1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.]), 'first': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]}
    The data type of mydic is 
    
    details(mydic['first'])
    The Value of mydic['first'] is (0, 1, 2, 3, 4, 5, 6)]
    The data type of mydic['first'] is 
    
    details(mydic.keys())
    The Value of mydic.keys() is ['second', 'third', 'first']
    The data type of mydic.keys() is 
    
    details(mydic['second'][0])
    The Value of mydic['second'][0] is a
    The data type of mydic['second'][0] is 
    

    I'm not sure if I put this in the right place, but I thought it might help. I hope it does.

提交回复
热议问题