简体   繁体   English

您如何计算列表中的最大重复次数?

[英]How do you calculate the greatest number of repetitions in a list?

If I have a list in Python like如果我在 Python 中有一个列表,例如

[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]

How do I calculate the greatest number of repeats for any element?如何计算任何元素的最大重复次数? In this case 2 is repeated a maximum of 4 times and 1 is repeated a maximum of 3 times.在这种情况下, 2最多重复 4 次, 1最多重复 3 次。

Is there a way to do this but also record the index at which the longest run began?有没有办法做到这一点,而且还记录最长运行开始的索引?

Usegroupby , it group elements by value:使用groupby ,它按值对元素进行分组:

from itertools import groupby
group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1])
print max(group, key=lambda k: len(list(k[1])))

And here is the code in action:这是实际的代码:

>>> group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1])
>>> print max(group, key=lambda k: len(list(k[1])))
(2, <itertools._grouper object at 0xb779f1cc>)
>>> group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3])
>>> print max(group, key=lambda k: len(list(k[1])))
(3, <itertools._grouper object at 0xb7df95ec>)

From python documentation:来自 python 文档:

The operation of groupby() is similar to the uniq filter in Unix. groupby() 的操作类似于 Unix 中的 uniq 过滤器。 It generates a break or new group every time the value of the key function changes每次 key 函数的值发生变化时,它都会生成一个 break 或 new group

# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D

If you also want the index of the longest run you can do the following:如果您还想要最长运行的索引,您可以执行以下操作:

group = groupby([1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1, 3, 3, 3, 3, 3])
result = []
index = 0
for k, g in group:
   length = len(list(g))
   result.append((k, length, index))
   index += length

print max(result, key=lambda a:a[1])

Loop through the list, keep track of the current number, how many times it has been repeated, and compare that to the most times youve seen that number repeated.循环遍历列表,跟踪当前数字、重复次数,并将其与您看到该数字重复的最多次数进行比较。

Counts={}
Current=0
Current_Count=0
LIST = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]
for i in LIST:
    if Current == i:
        Current_Count++
    else:
        Current_Count=1
        Current=i
    if Current_Count>Counts[i]:
        Counts[i]=Current_Count
print Counts

This is my solution:这是我的解决方案:

def longest_repetition(l):
    if l == []:
        return None

    element = l[0]
    new = []
    lar = []

    for e in l:            
        if e == element:
            new.append(e)
        else:
            if len(new) > len(lar):
                lar = new
            new = []
            new.append(e)
            element = e
    if len(new) > len(lar):
        lar = new    
    return lar[0]

-You can make new copy of the list but with unique values and a corresponding hits list. - 您可以制作列表的新副本,但具有唯一值和相应的命中列表。

-Then get the Max of hits list and get from it's index your most repeated item. - 然后获取点击列表的最大值,并从它的索引中获取您最重复的项目。

oldlist = ["A", "B", "E", "C","A", "C","D","A", "E"]
newlist=[]
hits=[]
for i in range(len(oldlist)):
    if oldlist[i] in newlist:
        hits[newlist.index(oldlist[i])]+= 1
    else:
        newlist.append(oldlist[i])
        hits.append(1);
#find the most repeated item
temp_max_hits=max(hits)
temp_max_hits_index=hits.index(temp_max_hits)
print(newlist[temp_max_hits_index])
print(temp_max_hits)

But I don't know is this the fastest way to do that or there are faster solution.但我不知道这是最快的方法还是有更快的解决方案。 If you think there are faster or more efficient solution, kindly inform us.如果您认为有更快或更有效的解决方案,请告知我们。

If you want it for just any element (ie the element with the most repetitions), you could use:如果您只希望它用于任何元素(即重复次数最多的元素),您可以使用:

def f((v, l, m), x):
    nl = l+1 if x==v else 1
    return (x, nl, max(m,nl))

maxrep = reduce(f, l, (0,0,0))[2];

This only counts continuous repetitions (Result for [1,2,2,2,1,2] would be 3 ) and only records the element with the the maximum number.这仅计算连续重复( [1,2,2,2,1,2]的结果将是3 )并且仅记录具有最大数量的元素。

Edit : Made definition of fa bit shorter ...编辑:使 fa 的定义更短...

i write this code and working easly:我编写此代码并轻松工作:

lst = [4,7,2,7,7,7,3,12,57]
maximum=0
for i in lst:
    count = lst.count(i)  
    if count>maximum:
        maximum=count
        indexx = lst.index(i)
print(lst[indexx])

This code seems to work:这段代码似乎工作:

l = [1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]
previous = None

# value/repetition pair
greatest = (-1, -1)
reps = 1

for e in l:
    if e == previous:
        reps += 1
    else:
        if reps > greatest[1]:
            greatest = (previous, reps)

        previous = e
        reps = 1

if reps > greatest[1]:
    greatest = (previous, reps)

print greatest

I'd use a hashmap of item to counter.我会使用项目的哈希图来反击。

Every time you see a 'key' succession, increment its counter value.每次看到“键”连续时,增加其计数器值。 If you hit a new element, set the counter to 1 and keep going.如果你击中了一个新元素,请将计数器设置为 1 并继续前进。 At the end of this linear search, you should have the maximum succession count for each number.在此线性搜索结束时,您应该获得每个数字的最大连续计数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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