2

I am trying to compile a python list based on first elements of nested list. But I am not sure what is the correct way to do that.

I have this nested list.

list1 = [[1, a, b, c], [2, b, c, d], [2, b, d, e], [1, c, a, d]]

I am trying to get an output like this.

output_list = [[1, [a, b, c], [c, a, d]], [2, [b, c, d], [b, d, e]]]
1
  • Take a look at this page: Link . A dictionary likely fits your need much better than a list like this. Commented Aug 4, 2021 at 19:58

2 Answers 2

4

Accumulating with a defaultdict, and then using a list comprehension at the end:

>>> list1 = [[1, 'a', 'b', 'c'], [2, 'b', 'c', 'd'], [2, 'b', 'd', 'e'], [1, 'c', 'a', 'd']]
>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> for first, *rest in list1:
...     d[first].append(rest)
... 
>>> [[first, *rest] for first, rest in d.items()]
[[1, ['a', 'b', 'c'], ['c', 'a', 'd']], [2, ['b', 'c', 'd'], ['b', 'd', 'e']]]
Sign up to request clarification or add additional context in comments.

1 Comment

This is genius. Thank you so much.
1
list1 = [[1, "a", 'b', 'c'], [2, 'b', 'c', "d"], [2, 'b', 'd', 'e'], [1, 'c', 'a', 'd']]
firstList = []
output_list = []
for i, list in enumerate(list1):
    if list[0] not in firstList:
        firstList.append(list[0])
        anotherList = []
        for j in range(1, len(list)):
            anotherList.append(list[j])
        bList = [list[0], anotherList]
        output_list.append(bList)
    else:
        place = firstList.index(list[0])
        anotherList = []
        for j in range(1, len(list)):
            anotherList.append(list[j])
        output_list[place].append(anotherList)
print(output_list)
>>>[[1, ['a', 'b', 'c'], ['c', 'a', 'd']], [2, ['b', 'c', 'd'], ['b', 'd', 'e']]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.