怎么对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
温馨提示:答案为网友推荐,仅供参考
相似回答