1.字典
1.1排序?
在Python中,要按照字典的值進行排序,可以按照以下步驟操作:
方法說明
- ?獲取鍵值對列表?:使用?
dict.items()
?獲取字典的鍵值對視圖。 - ?排序鍵值對?:使用?
sorted()
?函數,并通過?key
?參數指定按值排序。 - ?轉換回字典(可選)?:將排序后的列表轉換為字典(Python 3.7+ 支持有序字典)。
?
# 原始字典
d = {'apple': 10, 'banana': 5, 'orange': 20}# 按值升序排序鍵值對
sorted_items = sorted(d.items(), key=lambda x: x[1])# 輸出排序后的列表
print("按值升序排列的列表:", sorted_items)
# 輸出: [('banana', 5), ('apple', 10), ('orange', 20)]# 轉換為有序字典(Python 3.7+)
sorted_dict = dict(sorted_items)
print("排序后的字典:", sorted_dict)
# 輸出: {'banana': 5, 'apple': 10, 'orange': 20}# 按值降序排序(添加 reverse=True)
sorted_items_desc = sorted(d.items(), key=lambda x: x[1], reverse=True)
print("按值降序排列的列表:", sorted_items_desc)
# 輸出: [('orange', 20), ('apple', 10), ('banana', 5)]
?
?1.2統計字典的 key個數 collections.Counter(arr)
代碼實現了對數組?arr
?中元素的頻率統計,并按出現次數 ?從低到高? 排序。以下是代碼解析及優化建議:
group = collections.Counter(arr) freq = group.most_common()[::-1]
-
?
collections.Counter(arr)
?
統計?arr
?中每個元素的出現次數,返回?Counter
?對象(字典子類,鍵為元素,值為頻率)38。- 例如:
arr = [1, 2, 2, 3]
?→?group = {1:1, 2:2, 3:1}
。
- 例如:
-
?
most_common()
?
返回元素及其頻率的列表,按頻率 ?從高到低? 排序。若參數為空(如?most_common()
),返回所有元素23。- 示例結果:
[('b', 3), ('a', 2), ('c', 1)]
。
- 示例結果:
-
?
[::-1]
?
通過切片反轉列表,實現 ?從低到高? 排序56。- 最終結果:
[('c', 1), ('a', 2), ('b', 3)]
。
- 最終結果:
潛在問題與改進
1. ?相同頻率元素的順序不確定性?
most_common()
?對相同頻率的元素會保留原始插入順序(Python 3.7+ 字典有序),但若需嚴格按元素值排序,需額外處理8。- ?改進方法?:顯式指定排序規則。
-
freq = sorted(group.items(), key=lambda x: (x[1], x[0])) # 先按頻率升序,再按元素值升序
2. ?性能優化(適用于大數據量)?
most_common()
?的時間復雜度為 O(n log n),若僅需升序結果,可直接生成排序列表:freq = sorted(group.items(), key=lambda x: x[1]) # 直接生成升序列表,無需反轉
完整示例
from collections import Counter
arr = [1, 2, 2, 3, 3, 3]
group = Counter(arr) # 原始方法:反轉列表
freq_reversed = group.most_common()[::-1]
# 輸出:[(1, 1), (2, 2), (3, 3)]
# 改進方法:顯式排序
freq_sorted = sorted(group.items(), key=lambda x: x[1]) # 輸出:[(1, 1), (2, 2), (3, 3)]
方法對比
方法 | 時間復雜度 | 相同頻率元素的處理 | 適用場景 |
---|---|---|---|
most_common()[::-1] | O(n log n) | 保留插入順序 | 快速實現,無需嚴格排序 |
sorted() | O(n log n) | 可自定義排序規則(如元素值) | 需明確控制排序邏輯 |
注意事項
- ?空數組處理?:若?
arr
?為空,group
?也為空,freq
?會得到空列表,需在后續邏輯中處理5。 - ?頻率為0的元素?:
Counter
?默認不包含未出現的元素,但可通過?elements()
?遍歷所有可能鍵
def findLeastNumOfUniqueInts2(self, arr: list, k: int) -> int:group = collections.Counter(arr) # Counter({5: 2, 4: 1})print(group)freq=group.most_common()[::-1] # 逆序[(4, 1), (5, 2)]print(freq)ans=len(freq)for _ ,occ in freq:if k>=occ:ans-=-1k-=occelse:breakreturn ansprint(s.findLeastNumOfUniqueInts2([5, 5, 4], 1))Counter({5: 2, 4: 1})
題目:?1481. 不同整數的最少數目 - 力扣(LeetCode)
def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:arr_dict={}for i in arr:if i not in arr_dict:arr_dict[i]=1else:arr_dict[i]+=1# 對字典排序 sorted_dict=dict(sorted(arr_dict.items(),key=lambda x:x[1]))#print(sorted_dict)keys=sorted_dict.keys()ans=len(keys)for key in keys:if k-sorted_dict[key]>=0:#sorted_dict.remove(key)ans-=1k=k-sorted_dict[key]else:breakreturn ans