Simpler way to create dictionary of separate variables?

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

    Are you trying to do this?

    dict( (name,eval(name)) for name in ['some','list','of','vars'] )
    

    Example

    >>> some= 1
    >>> list= 2
    >>> of= 3
    >>> vars= 4
    >>> dict( (name,eval(name)) for name in ['some','list','of','vars'] )
    {'list': 2, 'some': 1, 'vars': 4, 'of': 3}
    

提交回复
热议问题