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
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]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.