cardamom
cardamom

Reputation: 7421

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))

output:

<class 'bool'>
<class 'int'>
<class 'float'>
<class 'tuple'>
<class 'bool'>
<class 'str'>
<class 'int'>
<class 'str'>
<class 'bool'>
<class 'tuple'>
<class 'float'>

Is there a command which will sort it according to types, that is, so the types land up in groups?

Upvotes: 1

Views: 90

Answers (3)

Ganesh Tata
Ganesh Tata

Reputation: 1195

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)]}

Upvotes: 1

omu_negru
omu_negru

Reputation: 4770

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)

Upvotes: 3

Moses Koledoye
Moses Koledoye

Reputation: 78556

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)]

Upvotes: 3

Related Questions