0
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
1

2 Answers 2

1

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']}
Sign up to request clarification or add additional context in comments.

1 Comment

I wanted to use dictionary , but this is an assignment for Uni , and they demand we use a List.
0
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']}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.