[英]Find the most common element in a list
在 Python 列表中查找最常見元素的有效方法是什么?
我的列表項可能無法散列,因此無法使用字典。 此外,在繪制的情況下,應返回索引最低的項目。 例子:
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
一個更簡單的單行:
def most_common(lst):
return max(set(lst), key=lst.count)
從這里借用,這可以與 Python 2.7 一起使用:
from collections import Counter
def Most_Common(lst):
data = Counter(lst)
return data.most_common(1)[0][0]
工作速度比 Alex 的解決方案快 4-6 倍,比 newacct 提出的 one-liner 快 50 倍。
要在出現關系時檢索列表中首先出現的元素:
def most_common(lst):
data = Counter(lst)
return max(lst, key=data.get)
提出了這么多解決方案,我很驚訝沒有人提出我認為顯而易見的解決方案(對於不可散列但可比較的元素)——[ itertools.groupby
][1]。 itertools
提供快速、可重用的功能,並允許您將一些棘手的邏輯委托給經過良好測試的標准庫組件。 考慮例如:
import itertools
import operator
def most_common(L):
# get an iterable of (item, iterable) pairs
SL = sorted((x, i) for i, x in enumerate(L))
# print 'SL:', SL
groups = itertools.groupby(SL, key=operator.itemgetter(0))
# auxiliary function to get "quality" for an item
def _auxfun(g):
item, iterable = g
count = 0
min_index = len(L)
for _, where in iterable:
count += 1
min_index = min(min_index, where)
# print 'item %r, count %r, minind %r' % (item, count, min_index)
return count, -min_index
# pick the highest-count/earliest item
return max(groups, key=_auxfun)[0]
當然,這可以寫得更簡潔,但我的目標是最大限度地清晰。 這兩個print
語句可以取消注釋,以便更好地查看運行中的機器; 例如,打印未注釋:
print most_common(['goose', 'duck', 'duck', 'goose'])
發出:
SL: [('duck', 1), ('duck', 2), ('goose', 0), ('goose', 3)]
item 'duck', count 2, minind 1
item 'goose', count 2, minind 0
goose
如您所見, SL
是一個對的列表,每對一個項目后跟項目在原始列表中的索引(實現關鍵條件,即如果具有相同最高計數的“最常見”項目 > 1,則結果必須是最早出現的)。
groupby
僅按項目分組(通過operator.itemgetter
)。 輔助函數,在max
計算期間每個分組調用一次,接收並在內部解包一個組 - 一個包含兩個項目(item, iterable)
的元組,其中可迭代的項目也是兩個項目的元組, (item, original index)
[[the SL
的項目]]。
然后輔助函數使用循環來確定組的可迭代項中的條目數和最小原始索引; 它將這些作為組合的“質量鍵”返回,最小索引符號已更改,因此max
操作將考慮“更好”原始列表中較早出現的那些項目。
如果這段代碼不太擔心時間和空間上的大 O 問題,它可能會簡單得多,例如......:
def most_common(L):
groups = itertools.groupby(sorted(L))
def _auxfun((item, iterable)):
return len(list(iterable)), -L.index(item)
return max(groups, key=_auxfun)[0]
相同的基本思想,只是表達得更簡單和緊湊......但是,唉,額外的 O(N) 輔助空間(以體現組的可迭代列表)和 O(N 平方)時間(以獲得L.index
每個項目)。 雖然過早的優化是編程中萬惡之源,但當 O(N log N) 可用時故意選擇 O(N 平方) 方法,這對可擴展性來說太過分了!-)
最后,對於那些更喜歡“oneliners”而不是清晰度和性能的人,還有一個額外的 1-liner 版本,帶有適當的名稱:-)。
from itertools import groupby as g
def most_common_oneliner(L):
return max(g(sorted(L)), key=lambda(x, v):(len(list(v)),-L.index(x)))[0]
你想要的在統計學中被稱為模式,Python當然有一個內置函數可以為你做這件事:
>>> from statistics import mode
>>> mode([1, 2, 2, 3, 3, 3, 3, 3, 4, 5, 6, 6, 6])
3
請注意,如果沒有“最常見的元素”,例如前兩個並列的情況,這將引發StatisticsError
,因為從統計學上講,這種情況下沒有模式。
如果沒有最低索引的要求,您可以使用collections.Counter
:
from collections import Counter
a = [1936, 2401, 2916, 4761, 9216, 9216, 9604, 9801]
c = Counter(a)
print(c.most_common(1)) # the one most common element... 2 would mean the 2 most common
[(9216, 2)] # a set containing the element, and it's count in 'a'
如果它們不可散列,您可以對它們進行排序並在結果上執行一個循環,計算項目(相同的項目將彼此相鄰)。 但是使它們可散列並使用字典可能會更快。
def most_common(lst):
cur_length = 0
max_length = 0
cur_i = 0
max_i = 0
cur_item = None
max_item = None
for i, item in sorted(enumerate(lst), key=lambda x: x[1]):
if cur_item is None or cur_item != item:
if cur_length > max_length or (cur_length == max_length and cur_i < max_i):
max_length = cur_length
max_i = cur_i
max_item = cur_item
cur_length = 1
cur_i = i
cur_item = item
else:
cur_length += 1
if cur_length > max_length or (cur_length == max_length and cur_i < max_i):
return cur_item
return max_item
這是一個 O(n) 的解決方案。
mydict = {}
cnt, itm = 0, ''
for item in reversed(lst):
mydict[item] = mydict.get(item, 0) + 1
if mydict[item] >= cnt :
cnt, itm = mydict[item], item
print itm
(reversed 用於確保它返回最低索引項)
對列表的副本進行排序並找到最長的運行。 您可以在使用每個元素的索引對其進行排序之前裝飾列表,然后在平局的情況下選擇從最低索引開始的運行。
單線:
def most_common (lst):
return max(((item, lst.count(item)) for item in set(lst)), key=lambda a: a[1])[0]
我正在使用 scipy stat 模塊和 lambda 執行此操作:
import scipy.stats
lst = [1,2,3,4,5,6,7,5]
most_freq_val = lambda x: scipy.stats.mode(x)[0][0]
print(most_freq_val(lst))
結果:
most_freq_val = 5
# use Decorate, Sort, Undecorate to solve the problem
def most_common(iterable):
# Make a list with tuples: (item, index)
# The index will be used later to break ties for most common item.
lst = [(x, i) for i, x in enumerate(iterable)]
lst.sort()
# lst_final will also be a list of tuples: (count, index, item)
# Sorting on this list will find us the most common item, and the index
# will break ties so the one listed first wins. Count is negative so
# largest count will have lowest value and sort first.
lst_final = []
# Get an iterator for our new list...
itr = iter(lst)
# ...and pop the first tuple off. Setup current state vars for loop.
count = 1
tup = next(itr)
x_cur, i_cur = tup
# Loop over sorted list of tuples, counting occurrences of item.
for tup in itr:
# Same item again?
if x_cur == tup[0]:
# Yes, same item; increment count
count += 1
else:
# No, new item, so write previous current item to lst_final...
t = (-count, i_cur, x_cur)
lst_final.append(t)
# ...and reset current state vars for loop.
x_cur, i_cur = tup
count = 1
# Write final item after loop ends
t = (-count, i_cur, x_cur)
lst_final.append(t)
lst_final.sort()
answer = lst_final[0][2]
return answer
print most_common(['x', 'e', 'a', 'e', 'a', 'e', 'e']) # prints 'e'
print most_common(['goose', 'duck', 'duck', 'goose']) # prints 'goose'
簡單的一條線解決方案
moc= max([(lst.count(chr),chr) for chr in set(lst)])
它將以其頻率返回最頻繁的元素。
您可能不再需要這個,但這是我為類似問題所做的。 (由於評論,它看起來比實際更長。)
itemList = ['hi', 'hi', 'hello', 'bye']
counter = {}
maxItemCount = 0
for item in itemList:
try:
# Referencing this will cause a KeyError exception
# if it doesn't already exist
counter[item]
# ... meaning if we get this far it didn't happen so
# we'll increment
counter[item] += 1
except KeyError:
# If we got a KeyError we need to create the
# dictionary key
counter[item] = 1
# Keep overwriting maxItemCount with the latest number,
# if it's higher than the existing itemCount
if counter[item] > maxItemCount:
maxItemCount = counter[item]
mostPopularItem = item
print mostPopularItem
以Luiz 的回答為基礎,但滿足“在繪制時應返回索引最低的項目”條件:
from statistics import mode, StatisticsError
def most_common(l):
try:
return mode(l)
except StatisticsError as e:
# will only return the first element if no unique mode found
if 'no unique mode' in e.args[0]:
return l[0]
# this is for "StatisticsError: no mode for empty data"
# after calling mode([])
raise
例子:
>>> most_common(['a', 'b', 'b'])
'b'
>>> most_common([1, 2])
1
>>> most_common([])
StatisticsError: no mode for empty data
ans = [1, 1, 0, 0, 1, 1]
all_ans = {ans.count(ans[i]): ans[i] for i in range(len(ans))}
print(all_ans)
all_ans={4: 1, 2: 0}
max_key = max(all_ans.keys())
4
print(all_ans[max_key])
1
#This will return the list sorted by frequency:
def orderByFrequency(list):
listUniqueValues = np.unique(list)
listQty = []
listOrderedByFrequency = []
for i in range(len(listUniqueValues)):
listQty.append(list.count(listUniqueValues[i]))
for i in range(len(listQty)):
index_bigger = np.argmax(listQty)
for j in range(listQty[index_bigger]):
listOrderedByFrequency.append(listUniqueValues[index_bigger])
listQty[index_bigger] = -1
return listOrderedByFrequency
#And this will return a list with the most frequent values in a list:
def getMostFrequentValues(list):
if (len(list) <= 1):
return list
list_most_frequent = []
list_ordered_by_frequency = orderByFrequency(list)
list_most_frequent.append(list_ordered_by_frequency[0])
frequency = list_ordered_by_frequency.count(list_ordered_by_frequency[0])
index = 0
while(index < len(list_ordered_by_frequency)):
index = index + frequency
if(index < len(list_ordered_by_frequency)):
testValue = list_ordered_by_frequency[index]
testValueFrequency = list_ordered_by_frequency.count(testValue)
if (testValueFrequency == frequency):
list_most_frequent.append(testValue)
else:
break
return list_most_frequent
#tests:
print(getMostFrequentValues([]))
print(getMostFrequentValues([1]))
print(getMostFrequentValues([1,1]))
print(getMostFrequentValues([2,1]))
print(getMostFrequentValues([2,2,1]))
print(getMostFrequentValues([1,2,1,2]))
print(getMostFrequentValues([1,2,1,2,2]))
print(getMostFrequentValues([3,2,3,5,6,3,2,2]))
print(getMostFrequentValues([1,2,2,60,50,3,3,50,3,4,50,4,4,60,60]))
Results:
[]
[1]
[1]
[1, 2]
[2]
[1, 2]
[2]
[2, 3]
[3, 4, 50, 60]
如果排序和散列都不可行,但相等比較 ( ==
) 可用,則這是明顯的慢速解決方案 (O(n^2)):
def most_common(items):
if not items:
raise ValueError
fitems = []
best_idx = 0
for item in items:
item_missing = True
i = 0
for fitem in fitems:
if fitem[0] == item:
fitem[1] += 1
d = fitem[1] - fitems[best_idx][1]
if d > 0 or (d == 0 and fitems[best_idx][2] > fitem[2]):
best_idx = i
item_missing = False
break
i += 1
if item_missing:
fitems.append([item, 1, i])
return items[best_idx]
但是,如果您的列表 (n) 的長度很大,則使您的項目可散列或可排序(如其他答案所建議的那樣)幾乎總是可以更快地找到最常見的元素。 散列平均為 O(n),排序最壞為 O(n*log(n))。
這里:
def most_common(l):
max = 0
maxitem = None
for x in set(l):
count = l.count(x)
if count > max:
max = count
maxitem = x
return maxitem
我有一種模糊的感覺,標准庫中的某處有一種方法可以為您提供每個元素的計數,但我找不到它。
>>> li = ['goose', 'duck', 'duck']
>>> def foo(li):
st = set(li)
mx = -1
for each in st:
temp = li.count(each):
if mx < temp:
mx = temp
h = each
return h
>>> foo(li)
'duck'
我需要在最近的一個程序中這樣做。 我承認,我無法理解亞歷克斯的回答,所以這就是我最終得到的。
def mostPopular(l):
mpEl=None
mpIndex=0
mpCount=0
curEl=None
curCount=0
for i, el in sorted(enumerate(l), key=lambda x: (x[1], x[0]), reverse=True):
curCount=curCount+1 if el==curEl else 1
curEl=el
if curCount>mpCount \
or (curCount==mpCount and i<mpIndex):
mpEl=curEl
mpIndex=i
mpCount=curCount
return mpEl, mpCount, mpIndex
我根據 Alex 的解決方案對其進行了計時,對於短列表,它的速度大約快了 10-15%,但是一旦你超過 100 個或更多元素(測試高達 200000),它就會慢大約 20%。
嗨,這是一個非常簡單的解決方案,具有線性時間復雜度
L = ['鵝','鴨','鴨']
def most_common(L):
current_winner = 0
max_repeated = None
for i in L:
amount_times = L.count(i)
if amount_times > current_winner:
current_winner = amount_times
max_repeated = i
return max_repeated
打印(最常見的(L))
“鴨”
其中 number 是列表中大部分時間重復的元素
最常見的元素應該是在數組中出現超過N/2
次的元素,其中N
是len(array)
。 下面的技術將在O(n)
時間復雜度內完成,僅消耗O(1)
輔助空間。
from collections import Counter
def majorityElement(arr):
majority_elem = Counter(arr)
size = len(arr)
for key, val in majority_elem.items():
if val > size/2:
return key
return -1
def most_frequent(List):
counter = 0
num = List[0]
for i in List:
curr_frequency = List.count(i)
if(curr_frequency> counter):
counter = curr_frequency
num = i
return num
List = [2, 1, 2, 2, 1, 3]
print(most_frequent(List))
def mostCommonElement(list):
count = {} // dict holder
max = 0 // keep track of the count by key
result = None // holder when count is greater than max
for i in list:
if i not in count:
count[i] = 1
else:
count[i] += 1
if count[i] > max:
max = count[i]
result = i
return result
mostCommonElement(["a","b","a","c"]) -> "a"
def most_common(lst):
if max([lst.count(i)for i in lst]) == 1:
return False
else:
return max(set(lst), key=lst.count)
def popular(L):
C={}
for a in L:
C[a]=L.count(a)
for b in C.keys():
if C[b]==max(C.values()):
return b
L=[2,3,5,3,6,3,6,3,6,3,7,467,4,7,4]
print popular(L)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.