简体   繁体   中英

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

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 ?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM