[英]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.