=Start=
缘由:
总结一下最近在编码过程中遇到的一些Python知识点,方便以后快速参考、学习。
正文:
参考解答:
Yes, the order of elements in a python list is persistent.
根据插入顺序决定元素的实际位置。
# 期望达到的效果
>>> most_common(['duck', 'duck', 'goose'])
'duck'
>>> most_common(['goose', 'duck', 'duck', 'goose'])
'goose'
# 方法一
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]
# 方法二
def most_common(lst):
return max(set(lst), key=lst.count)
#方法三
from collections import Counter
def most_common(lst):
data = Counter(lst)
return max(lst, key=data.get)
# 即,给定一个list,调用某个函数返回该list中出现次数最多的元素。 max(set(list_in), key=list_in.count) # Python 2.7及以上版本 from collections import Counter data = Counter(your_list_in_here) data.most_common() # Returns all unique items and their counts data.most_common(1) # Returns the highest occurring item
参考链接:
- https://stackoverflow.com/questions/13694034/is-a-python-list-guaranteed-to-have-its-elements-stay-in-the-order-they-are-inse
- https://stackoverflow.com/questions/1518522/find-the-most-common-element-in-a-list
- https://stackoverflow.com/questions/10797819/finding-the-mode-of-a-list
=END=