當前位置:成語大全網 - 新華字典 - 怎麽對python中列表類型進行分組

怎麽對python中列表類型進行分組

如下,將不同的類型及值放到字典中

例如列表lst有int,list,tuple,dict,str,float等類型。

lst = [1,2,3,'54',45.0,'784','string',[1,2,3],(3,6,7),{"no1":1,"no2":2}]

#定義dict_lstype,來對列表lst進行分組

dict_lstype={}

for i in lst:

type_i = type(i)

#如果i的類型在字典中已經存在,則進行追加;如果不存在,則新增壹個類型的列表

if type_i in dict_lstype:

dict_lstype[type_i].append(i)

else:

dict_lstype[type_i] = [i]

print dict_lstype