在python中排序不同的数据类型


li=[22 , True , 22/7 , {"Staat":"Deutschland" , "Stadt" : "Berlin"}  , 69 
, ["Python" , "C++" , "C#"] ,
("Kairo" , "Berlin" , "Amsterdam")  , False , "Apfel" , 55 ]

我如何在多个列表中排序这个列表,每个列表对应一个数据类型(int, str, dict等)

for x in li:

if type(x) == float:
double = x
print("double" ,double )
elif type(x) == str:
strings = x
print("strings" ,strings)

it is too long ,  and its does not combine similar data in one list

您可以使用type(x)作为键的字典:

lists_by_type={};
for x in li:
print (x)
if type(x) in lists_by_type.keys():
lists_by_type[type(x)].append(x)
else:
lists_by_type[type(x)]=[x]

这将为您提供一个包含每种数据类型列表的字典

的结果类似于:

{int: [22, 69, 55],
bool: [True, False],
float: [3.142857142857143],
dict: [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}],
list: [['Python', 'C++', 'C#']],
tuple: [('Kairo', 'Berlin', 'Amsterdam')],
str: ['Apfel']}
li=[22 , True , 22/7 , {"Staat":"Deutschland" , "Stadt" : "Berlin"}  , 69 
, ["Python" , "C++" , "C#"] ,
("Kairo" , "Berlin" , "Amsterdam")  , False , "Apfel" , 55 ]

# this function groups elements by type
def group(lists):
groups = dict()
for i in lists:
a = str(type(i)).split(" ")
typ = a[1][1:-2]
if typ in groups.keys():
groups[typ].append(i)
else:
groups[typ] = [i]
return groups

print(group(li))

结果:

{'int': [22, 69, 55], 'bool': [True, False], 'float': [3.142857142857143], 'dict': [{'Staat': 'Deutschland', 'Stadt': 'Berlin'}], 'list': [['Python', 'C++', 'C#']], 'tuple': [('Kairo', 'Berlin', 'Amsterdam')], 'str': ['Apfel']}

最新更新