我认为我的问题将有助于说明为什么这个问题是有用的,它可能会让你更深入地了解如何回答这个问题。我写了一个小函数来对代码中的各种变量进行快速内联头部检查。基本上,它列出了变量名、数据类型、大小和其他属性,因此我可以快速捕捉到我所犯的任何错误。代码很简单:
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)))
所以如果你有一些复杂的字典/列表/元组的情况,让解释器返回你分配的变量名会很有帮助。例如,这里有一个奇怪的字典:
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 <type 'dict'>
details(mydic['first'])
The Value of mydic['first'] is (0, 1, 2, 3, 4, 5, 6)]
The data type of mydic['first'] is <type 'list'>
details(mydic.keys())
The Value of mydic.keys() is ['second', 'third', 'first']
The data type of mydic.keys() is <type 'tuple'>
details(mydic['second'][0])
The Value of mydic['second'][0] is a
The data type of mydic['second'][0] is <type 'str'>
我不确定我是否把它放在正确的地方,但我想它可能有帮助。我希望如此。