查找列表中最常见的对象及其出现的位置

Find most common object of a list and the locations of its appearances

我想在列表中找到最常见的元素,但此外我还想知道每个元素出现的位置。 例如,如果我有以下数组:

array([[[1503,    0]],

       [[6600,    0]],

       [[1503,    0]],

       [[6320,    0]],

       [[1503,    0]]], dtype=int64)

我想要的输出是这样的:1503, [0, 2, 4] , 其中第一个输出 (1503) 是我列表中最常见的元素,第二个输出 ([0, 2, 4]) 是位置列表。

我使用了以下代码片段:

from collections import Counter

def find_majority(accounts):
    accounts_count = Counter(accounts)
    top_account = accounts_count.most_common(1)
    if len(top_account)>1 and top_account[0][1] == top_account[1][1]:
        # It is a tie
        return 0
    return top_account[0][0]

它给了我最常见的元素,但我不知道如何升级此代码片段以找到位置。

像这样使用np.where

import numpy as np
from collections import Counter

accounts = np.array([1503, 6600, 1503, 6320, 1503])

def find_majority(accounts):
    accounts_count = Counter(accounts)
    top_account = accounts_count.most_common(1)
    if len(top_account)>1 and top_account[0][1] == top_account[1][1]:
        # It is a tie
        return None, None
    return top_account[0][0], np.where(accounts == top_account[0][0])[0]
    
print(find_majority(accounts))

输出:

(1503, array([0, 2, 4]))

Find the most common element in a list 阅读更多内容。

因为您已经有了要查找的值,所以您可以使用 np.where,它将条件作为输入。如果说你最常见的元素是 1503,np.where(array == 1503) returns 一个与你所在位置的 True 相同形状的数组。