li=[22 , True , 22/7 , {"Staat":"Deutschland" , "Stadt" : "Berlin"} , 69
, ["Python" , "C " , "C#"] ,
("Kairo" , "Berlin" , "Amsterdam") , False , "Apfel" , 55 ]
How can I sort this list in multiple lists , one list for each data type (int , str , dict, etc..)
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
CodePudding user response:
you could use a dictionary that has type(x) as keys:
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]
This gives you then a dictionary with lists for each data type
result would be something like:
{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']}
CodePudding user response:
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))
RESULT:
{'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']}