Skip to content Skip to sidebar Skip to footer

Is There A Command Which Will Sort A Python List By Data Type?

Given the following list: l = [True, 3, 7.3, (5,6), True, 'orange', 25, 'banana', False, (4,5), 9.2] which contains a mixture of types: for element in l: print (type(element))

Solution 1:

You can use the string representation of the types for sorting:

>>> sorted(l, key=lambda x: str(type(x)))
[True, True, False, 7.3, 9.2, 3, 25, 'orange', 'banana', (5, 6), (4, 5)]

Similar types will be grouped together maintaining the initial order in which they appeared.

In Python 2, type objects can be sorted directly, and you can pass type directly as the key function:

>>> sorted(l, key=type)
[True, True, False, 7.3, 9.2, 3, 25, 'orange', 'banana', (5, 6), (4, 5)]

Solution 2:

a more readable solution would be ( along with the keys):

s = sorted([(x, x.__class__.__name__) for x in l], key=lambda x: x[1])
print(s)

Solution 3:

Building on @omu_negru's solution -

groups = dict()
for element in l:
    element_type = element.__class__.__name__
    if element_type not in groups:
        groups[element_type] = list()
    groups[element_type].append(element)
print(groups)
#  groups - {'bool': [True, True, False], 'float': [7.3, 9.2], 'int': [3, 25], 'str': ['orange', 'banana'], 'tuple': [(5, 6), (4, 5)]}

Post a Comment for "Is There A Command Which Will Sort A Python List By Data Type?"