Python的一些小知识点_12


=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

 

参考链接:

=END=

,

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注