Answer the question
In order to leave comments, you need to log in
[[+content_image]]
How to group two lists and sort by number of matches?
There are two lists
first_names=
last_names=[[<User: username1>],[<User: username3>],[<User: username4>]]
intersection=[[<User: username1>],[<User: username3>]]
subtraction=[[<User: username2>],[<User: username4>]]
list_of_all.append(intersection)
list_of_all.append(subtraction)
list_of_all=[[<User: username1>],[<User: username3>],[<User: username2>],[<User: username4>]]
context["by_names"].append(list(set(first_names) & set(last_names)))
context["by_names"].append(list(set(last_names) - set(first_names)))
Answer the question
In order to leave comments, you need to log in
from itertools import chain
from collections import Counter
list1 = [1, 2, 3]
list2 = [1, 3, 4]
list3 = [1, 4, 5]
counter = Counter(chain(list1, list2, list3))
ordered = sorted(
set(list1).union(list2).union(list3), key=lambda k: counter[k], reverse=True
)
print(ordered)
The intersection of sets is unlikely to achieve adequate relevance. It can be told that an object has two or more occurrences (if the intersection of two lists, of course). Thus, objects with 10 and 2 occurrences will be on the same level.
Easier to count occurrences.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question