簡體   English   中英

從第三個列表中找到兩個列表中最常見的數字,獲取最常見元素的列表

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

我在這里創建了這段代碼:

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]

它旨在獲取第三個數組中最常見的元素。 例如, list_2中只有兩個公共元素,而list_1中只有三個。 我希望能夠將list_1識別為正確的。 為什么要打印list_2

只需遍歷 eash 可能的列表,然后為每個計算共同項目的數量,保留最大的項目

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

可以通過內置的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)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM