[[+content_image]]
Y
Y
Yeldos Adetbekov2015-11-23 20:04:36
Django
Yeldos Adetbekov, 2015-11-23 20:04:36

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>]]

did something like this but didn't work
context["by_names"].append(list(set(first_names) & set(last_names)))
context["by_names"].append(list(set(last_names) - set(first_names)))

I need to sort the most appropriate option
and how to submit the list
Please help, @Kitaev))

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
A
angru, 2015-11-24
@dosya97

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)

R
Roman Kitaev, 2015-11-23
@deliro

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 question

Ask a Question

731 491 924 answers to any question