如果我有一個像你如何計算列表中最大的重複次數?
[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]
如何計算重複最大數量的任何元素在Python列表?在這種情況下,2
重複最多4次,並且1
重複最多3次。
有沒有辦法做到這一點,但也記錄最長的運行開始的索引?
如果我有一個像你如何計算列表中最大的重複次數?
[1, 2, 2, 2, 2, 1, 1, 1, 2, 2, 1, 1]
如何計算重複最大數量的任何元素在Python列表?在這種情況下,2
重複最多4次,並且1
重複最多3次。
有沒有辦法做到這一點,但也記錄最長的運行開始的索引?
使用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])))
這裏是在動作的代碼:
>>> 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>)
從Python文檔:
操作groupby()的類似 到Unix中的uniq過濾器。它 產生中斷或新組的每個 時間的關鍵功能 價值變動
# [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
如果你也想最長運行的指數,你可以做到以下幾點:
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])
此代碼似乎工作:
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
我會使用項目的HashMap來應對。
每當你看到一個'鑰匙'繼承,增加其計數器值。如果您點擊一個新元素,請將計數器設置爲1並繼續。在線性搜索結束時,您應該爲每個數字設置最大連續數。
循環遍歷列表,跟蹤當前的數字,重複了多少次,並將其與您所看到的重複次數的次數進行比較。
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
如果你只想要它任何元素(即最重複的元素),你可以使用:
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];
這隻計算連續重複(結果爲[1,2,2,2,1,2]
將爲3
),並且只記錄具有最大數量的元素。
編輯:FA作出定義有點短...
這是我的解決方案:
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]
- 可以使列表,但具有獨特的價值和相應的命中新副本名單。
- 然後獲取最大匹配列表並從它的索引中獲取最重複的項目。
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)
但我不知道這是最快的方法,或者有更快的解決方案。 如果您認爲有更快或更有效的解決方案,請通知我們。
這聽起來你正在尋找列表中最長的運行;你可能想要編輯你的問題來說明清楚。 – las3rjock 2009-05-19 23:43:11
特別是每個數字的最長運行 – Sparr 2009-05-19 23:43:39
是的Sparr是正確的。有沒有辦法做到這一點,但也記錄最長的運行開始的索引? – hekevintran 2009-05-19 23:51:08