如何获取该列表中值最大的元素的索引列表

时间:2017-02-12 06:21:19

标签: python-3.x

假设我有一个列表l=[3,4,4,2,1,4,6] 我想获得这个列表的一个子集,其中包含值为max(l)的元素索引。 在这种情况下,索引列表将为[1,2,5]

我正在使用这种方法来解决一个问题,例如提供了一个数字列表

l=[1,2,3,4,3,2,2,3,4,5,6,7,5,4,3,2,2,3,4,3,4,5,6,7]

我需要识别元素的最大出现次数,但是如果多于1个元素出现相同的次数, 我需要选择幅度更大的元素, 假设我在l上应用一个计数器并获得{1:5,2:5,3:4...},我必须选择'2'而不是'1'。 请建议如何解决这个问题

编辑 - 问题就像这样开始, 1)提供列表作为输入

l=[1 4 4 4 5 3]

2)我在此处运行一个计数器以获取每个唯一元素的计数

3)我需要获取值最大的键

4)假设Counter对象包含多个值最大的条目, 在Counter{1:4,2:4,3:4,5:1}中 我必须选择3作为其值为4的键。

5)到目前为止,我已经能够获得Counter对象,我使用k=counter.keys();v=counter.values()分隔了键/值列表

6)我想得到v值最大的索引 如果我运行v.index(max(v)),我得到第一个索引,其值与最大值匹配,但我想获取其值为max的索引列表,这样我就可以获得相应的键列表并获得最大值键入该列表。

2 个答案:

答案 0 :(得分:0)

使用长列表,使用NumPy或任何其他线性代数会有所帮助,否则您只需使用

print (df) B 0 k1[a-token] 1 v1 2 v2 3 k2[a-token] 4 v1' 5 k3[a-token] 6 v1" 7 v2" 8 v3" 9 k2[a-token] 10 v1' df.insert(0, 'A', df['B'].str.extract('(.*)\[a-token\]', expand=False).ffill()) df = df[df['A'].duplicated()].reset_index(drop=True) print (df) A B 0 k1 v1 1 k1 v2 2 k2 v1' 3 k3 v1" 4 k3 v2" 5 k3 v3" 6 k2 k2[a-token] 7 k2 v1'

mask

然而,这些只返回了许多argmax中的一个。

因此,对于您的问题,您可以选择反转数组,因为您希望以后出现的最大值:

df.insert(0, 'A', df['B'].str.extract('(.*)\[a-token\]', expand=False).ffill()) df = df[~df['B'].str.contains('\[a-token]')].reset_index(drop=True) print (df) A B 0 k1 v1 1 k1 v2 2 k2 v1' 3 k3 v1" 4 k3 v2" 5 k3 v3" 6 k2 v1'

答案 1 :(得分:0)

如果我理解正确,以下应该做你想要的。

from collections import Counter

def get_largest_most_freq(lst):
    c = Counter(lst)
    # get the largest frequency
    freq = max(c.values())
    # get list of all the values that occur _max times
    items = [k for k, v in c.items() if v == freq]
    # return largest most frequent item
    return max(items)

def get_indexes_of_most_freq(lst):
    _max = get_largest_most_freq(lst)
    # get list of all indexes that have a value matching _max
    return [i for i, v in enumerate(lst) if v == _max]

>>> lst = [3,4,4,2,1,4,6]
>>> get_largest_most_freq(lst)
4
>>> get_indexes_of_most_freq(lst)
[1, 2, 5]
>>> lst = [1,2,3,4,3,2,2,3,4,5,6,7,5,4,3,2,2,3,4,3,4,5,6,7]
>>> get_largest_most_freq(lst)
3
>>> get_indexes_of_most_freq(lst)
[2, 4, 7, 14, 17, 19]