Mirs405
Mirs405

Reputation: 77

Grouping by items in list of lists in Python

I have a Python list that looks like this:

mylist = [[1,apple,orange,banana],[2,apple],[3,banana,grapes]]

how can i transform it to something like this:

new_list = [[apple,1,2],[orange,1],[banana,1,3],[grapes,3]

basically i want to create new list of lists that is grouped by each of the fruits in the original list of lists with the number in the first index

Upvotes: 0

Views: 236

Answers (1)

azro
azro

Reputation: 54168

You may use a defaultdict to group the indexes per fruit, then concatenate key and values

from collections import defaultdict
mylist = [[1, "apple", "orange", "banana"], [2, "apple"], [3, "banana", "grapes"]]

result = defaultdict(list)
for idx, *fruits in mylist:
    for fruit in fruits:
        result[fruit].append(idx)
print(result)  # {'apple': [1, 2], 'orange': [1], 'banana': [1, 3], 'grapes': [3]}

result = [[key, *values] for key, values in result.items()]
print(result)  # [['apple', 1, 2], ['orange', 1], ['banana', 1, 3], ['grapes', 3]]

Upvotes: 2

Related Questions