python返回一个列表中出现次数最多的元素及数量。

python返回一个列表中出现次数最多的元素

一个最简单的方法:

lst = [‘小李’, ‘小张’, ‘小王’, ‘小张’, ‘小杜’, ‘小杜’, ‘小袁’, ‘小张’]
print(max(lst, key=lst .count))

------------------------------------------------------------------------------------------------------------------

python 返回一个列表中出现次数最多的元素

def max_list(lt):
temp = 0
for i in lt:
    if lt.count(i) > temp:
        max_str = i
        temp = lt.count(i)
return max_str

n = [1,2,2,2,3,3,3,3,4,4]
print(max_list(n))

---------------------------------------------------------------

下面是随便写的:

输出姓名最多的人名及个数

lst = [‘小李’, ‘小张’, ‘小王’, ‘小张’, ‘小杜’, ‘小杜’, ‘小杜’, ‘小袁’, ‘小张’]
lst2 = set()

print(max(lst, key=lst.count))

dicts = {}
tsum = 0
k52=0
for i in set(lst):
dicts[i] = 0

print(dicts)

dictsed = dicts

for i1 in lst:
for i2 in dicts.keys():
if i1 == i2:
dictsed[i2] = dictsed.get(i2) + 1

print(dictsed)

dictsedsum = {}
for k, j in dictsed.items():

if j >= tsum:
    tsum = j
    dictsedsum.clear()
    dictsedsum[k] = j

print(dictsedsum)

for i in dictsedsum.values():
k52=i

disuccess={}
for k1, j1 in dictsed.items():
if j1 == k52:
disuccess[k1]=j1

print(disuccess)

-----------------------------------------------------------------------------------------

方法2

找出重复的字符及数量

listNum = [2, 2, ‘a’, ‘a’, ‘b’, ‘b’, ‘c’, 1, 1, ‘’, ‘’]
intNum = 0
dictA = {}
dictB = {}

for iA in listNum:
if iA in dictA.keys():
dictA[iA] = dictA.get(iA) + 1
if dictA.get(iA) > intNum:
intNum = dictA.get(iA)
else:
dictA[iA] = 1

for k, j in dictA.items():
if intNum == j:
dictB[k] = j

print(dictB)

-------------------------------------------------------------------------------------

方法3、
nb = [5,‘a’,‘a’,‘b’,‘b’,1,3,’’,’’]
intNum=0
dictB={}
for i in nb:
if nb.count(i)>=intNum:
intNum=nb.count(i)

先判断最大元素的数量值。

print(intNum)

再根据元素的最大数量,求元素及数量,放在字典中。

for i1 in nb:
if nb.count(i1)==intNum:
dictB[i1]=intNum
print(dictB)

-------------------------------------------------------------------

方法4、

n = [1, 1, 2, 2, 3]
dictns = {}

判断最大元素是谁

na = max(n, key=n.count)

判断最多元素的个数

inum = n.count(na)

挑选出最多元素有哪几个。

for i in n:
if n.count(i) == inum:
dictns[i] = inum
print(dictns)

你可能感兴趣的:(python)