0

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 Answers 2

1
grouped = {}
for k, v in zip(list2, list3):
    grouped.setdefault(k, []).append(v)
new_list = [grouped[k] for k in list1]
Sign up to request clarification or add additional context in comments.

Comments

0

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)

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.