Python統計數列中元素出現的次數並進行排序

2021-09-26 11:00:46 字數 921 閱讀 5395

輸入:list,例如['d', 'f', 'g', 'f', 'e', 'z', 'f', 'a', 'a']

輸出:list,統計每個元素出現的次數,並按照從高到低的順序排序,例如[('f', 3), ('a', 2), ('d', 1), ('g', 1), ('e', 1), ('z', 1)]

count()方法用於統計字串裡某個字元出現的次數。可選引數為在字串搜尋的開始與結束位置。

sorted()函式對所有可迭代的物件進行排序操作,返回的是乙個新的 list。其中reverse = true 表示降序。

from collections import counter

# 根據數列中字母出現的次數和ascii的大小,進行排序。

l1 = ['d', 'f', 'g', 'f', 'e', 'z', 'f', 'a', 'a']

d2 = counter(l1)

sorted_x = sorted(d2.items(), key=lambda x: x[1], reverse=true)

print(sorted_x)

set()函式建立乙個無序不重複元素集,可進行關係測試,刪除重複資料,還可以計算交集、差集、並集等。

l1 = ['d', 'f', 'g', 'f', 'e', 'z', 'f', 'a', 'a']

set01 = set(l1)

dict01 =

sorted_x = sorted(dict01.items(), key=lambda x: x[1], reverse=true)

print(sorted_x)

Python 統計序列中元素出現次數

import sys import random from collections import counter reload sys sys.setdefaultencoding utf 8 data list random.randint 1,20 for in range 10 從1 20隨機...

Python教程 如何統計序列中元素的出現頻度

實際操作中,我們該如何統計序列中元素的出現頻度,這篇python實戰教程手把手教你!實際案例 from random import randint 使用列表解析生成30個元素 在0 20範圍內 data randint 0,20 for in xrange 30 print type data 使用...

排序數列中元素出現次數問題

於 排序數列中元素出現次數問題 這裡採用折半法給出兩種思路 1 找到元素在陣列中的乙個索引位置,由於是陣列是有序排列,所有在這個位置左右移動,就可以找出其所有出現的位置 2 通過折半法找到元素的最大索引位置與最小索引位置,然後兩個索引位置相減再加一,就是元素的出現的次數。方法1中查詢元素位置的方法複...