我写了一些小功能来快速浏览列表,字典等...
我现在发现以下代码很少出现行为
def main():
Debug(['S',1,'G',False])
def Debug(Var,Name='noName'):
Space =' '
if 'list' in type(Var).__name__:
print('printing:',type(Var).__name__,Name,'\n')
No=0
for Item in Var:
No += 1
if 'str' in type(Item).__name__:
print ( Space + Name + ' Item no.: ' + str(No) + ' {0:5s} <{1:s}>'.format( type(Item).__name__ , Item) )
print ( Space + Name + ' Item no.: ' + str(No) + ' {0:5s} {1:s}' .format(type(Item).__name__,'<'+Item+'>'))
else:
print (Space + Name + ' Item no.: ' + str(No)+' {:5s}'.format(type(Item).__name__),Item)
print('\n',type(Var).__name__,Name,'has',len(Var),'entries\n')
return
输出为:
printing: list noName
noName Item no.: 1 str
noName Item no.: 1 str
noName Item no.: 2 int 1
noName Item no.: 3 str <G>
noName Item no.: 3 str <G>
noName Item no.: 4 bool False
list noName has 4 entries
有人知道为什么不打印'S'吗? 甚至前面的空格都不见了...
答案 0 :(得分:0)
请注意命名约定和isinstance
的使用:
def debug(var, name='noName'):
if isinstance(var, list):
print('printing:', type(var), var, '\n')
no = 0
for index, item in enumerate(var): # enumerate gives us the index and the element
if isinstance(item, str):
print(f" {name} Item no.: {index + 1} {str(type(item)):5s} <{item:s}>")
else:
print(f" {name} Item no.: {index + 1} {str(type(item)):5s}")
print(f'\n{str(type(var))} {name} has {len(var)} entries\n')
return
if __name__ == '__main__':
debug(['S',1,'G',False])
输出:
printing: <class 'list'> ['S', 1, 'G', False]
noName Item no.: 1 <class 'str'> <S>
noName Item no.: 2 <class 'int'>
noName Item no.: 3 <class 'str'> <G>
noName Item no.: 4 <class 'bool'>
<class 'list'> noName has 4 entries