How To Group Sublist's With Matching Values
I have a list with sublist's in it and want to group them based on a common value. For example: my_list = [['John', 1], ['Mark', 3], ['Peter', 5], ['Mark', 6], ['Mark', 33], ['John
Solution 1:
Use itertools.groupby
.
Since you want to only group by the first element of each sublist, you must supply a custom key.
import itertools
[list(g) for _, g in itertools.groupby(sorted(my_list), lambda x: x[0])]
Output:
[[['John', 1], ['John', 2]],
[['Mark', 3], ['Mark', 6], ['Mark', 33]],
[['Peter', 5]]]
Solution 2:
Nice question. I prefer the answer by @user3483203 using itertools.groupby
but here is a solution with no imports;
result = []
name_to_index = {}
for l in my_list:
if l[0] in name_to_index:
result[name_to_index.get(l[0])].append(l)
else:
result.append([l])
name_to_index[l[0]] = len(result) - 1
Output:
[[['John', 1], ['John', 2]], [['Mark', 3], ['Mark', 6], ['Mark', 33]], [['Peter', 5]]]
Post a Comment for "How To Group Sublist's With Matching Values"