-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdvanceListSort.py
More file actions
29 lines (23 loc) · 898 Bytes
/
Copy pathAdvanceListSort.py
File metadata and controls
29 lines (23 loc) · 898 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from collections import defaultdict
def advanced_sort(lst):
"""
Create a function that takes a list of numbers or strings
and returns a list with the items from the original list
stored into sublists. Items of the same value should be in
the same sublist.
Examples
advanced_sort([2, 1, 2, 1]) ➞ [[2, 2], [1, 1]]
advanced_sort([5, 4, 5, 5, 4, 3]) ➞ [[5, 5, 5], [4, 4], [3]]
advanced_sort(["b", "a", "b", "a", "c"]) ➞ [["b", "b"], ["a", "a"], ["c"]]
Notes
The sublists should be returned in the order of each element's
first appearance in the given list.
"""
d = defaultdict(list)
for i in lst:
d[i].append(i)
return [l for l in d.values()]
if __name__ == "__main__":
print(advanced_sort([2, 1, 2, 1]))
print(advanced_sort([5, 4, 5, 5, 4, 3]))
print(advanced_sort(["b", "a", "b", "a", "c"]))