0
votes

I've got 3 lists like so:

list1 = [1,2]
list2 = [1,1,1,2,2]
list3 = ["comment1", "comment2", "comment3", "comment4", "commment5"]

list2 and list3 are always the same length.

What I'm trying to accomplish is to create a new list of lists by comparing list1 with list2 and when the item in list2 equals the item in list1, append the "comment" in list3 with the same index in list2 to a new list. So in this case the result should be:

new_list' = [["comment1", "comment2", "comment3"],["comment4", "comment5"]]

I hope I made it clear enough....

2

2 Answers

1
votes
grouped = {}
for k, v in zip(list2, list3):
    grouped.setdefault(k, []).append(v)
new_list = [grouped[k] for k in list1]
0
votes

Like many problems in Python, this should be solved with zip:

# Make result list
new_list = [[] for _ in range(len(list1))]
# Make cheap lookup to find the appropriate list to append to
new_lookup = dict(zip(list1, new_list))
for addkey, comment in zip(list2, list3):
    new_lookup[addkey].append(comment)