Merge Nested List By First Value In Each List In Python
I have a version of this code working but it seems overly complex. This is the simplified version im getting stuck on. in python3. list1 = [['a', 'b'], ['a', 'c'], ['a', 't'], [
Solution 1:
Modding Darryl's a bit:
d = {}
forhead, *tailin lst:
d.setdefault(head, [head]).extend(tail)
lst2 = list(d.values())
Solution 2:
A simplfied construction is the following two steps.
d = {}
for sublist in lst:
d.setdefault(sublist[0], []).extend(sublist[1:])
lst2 = [[k] + v for k, v in d.items()]
print(lst2)
>>> [['a', 'b', 'c', 't'], ['x', 'f', 'g'], ['d', 'z']]
Explanation
(1) Dictionary d places items with the same first element as a dictionary key, with values corresponding to the remaining elements to produce:
{'a': ['b', 'c', 't'], 'x': ['f', 'g'], 'd': ['z']}
(2) Next, the list comprehension uses the key of each dictionary entry as the first element of a sublist and the value of the items as the remaining elements to produce the desired result
Post a Comment for "Merge Nested List By First Value In Each List In Python"