Home > Net >  Find the most common number in two lists from a third list, get list with most common elements
Find the most common number in two lists from a third list, get list with most common elements

Time:07-17

I've created this code here:

list_1 = [1.04, 1.1, 1.87, 1.05, 1.09, 1.53]
list_2 = [4.36, 1.92, 7.20, 6.12]

common_items = [4.36, 1.92, 1.04, 1.1, 1.87]

most_common = []

for x in common_items:
    for y in [list_1, list_2]:
        common = set(common_items).intersection(y)
        common = list(common)

        for z in common:
            if z in y:
                most_common = y

print(most_common)

>>> [4.36, 1.92, 7.2, 6.12]

It is intended to get the elements that are most common inside of the third array. For example, there are only two common elements from list_2, but three from list_1. I want to be able to identify list_1 as the correct one. Why is it printing list_2?

CodePudding user response:

Just iterate over eash possible list, then for each compute the number of items in common, keep the one with the max

most_common = []
most_common_count = 0

for y in [list_1, list_2]:
    common_count = len(set(common_items).intersection(y))
    if common_count > most_common_count:
        most_common_count = common_count
        most_common = y

Can be achieved with builtin max

common_items = {4.36, 1.92, 1.04, 1.1, 1.87}

most_common = max([list_1, list_2],
                  key=lambda y: len(common_items.intersection(y)))
  • Related