網站首頁 編程語言 正文
一. 定義
set是一個無序且不重復的元素集合
set和dict類似,是一組key的集合,但不存儲value
set有以下特性:
由于key不能重復,所有set中沒有重復的key
元素為不可變對象(不能將可變類型字典或者列表作為元素)
二. 創建set
1. 直接使用{}創建新的set并初始化
set1 = {1, 2, 3, (4, 5, 6), "good news"}
2. 使用set關鍵字來創建
set2 = set([1, 2, 3]) #相當于set2 = {1, 2, 3}, set函數只能傳入一個參數
set3 = set((1,2,3)) #相當于set3 = {1,2,3}
set4 = set({'a':1,'b':2,'c':3}) #相當于set4 = {'a','b','c'}
3. 創建空的set
如果要創建一個空的set,只能使用set()關鍵字,因為如果使用set1={}這種方式,那么set1會被聲明為一個空的字典
三. 基本操作
1. 重復的操作在set中自動被過濾
>>> s = set([1, 1, 2, 2, 3, 3])
>>> s
{1, 2, 3}
2. 通過add(key)方法可以添加元素到set中,可以重復添加,但不會有效果
>>> s = {1, 2, 3}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.add(4)
>>> s
{1, 2, 3, 4}
3. 通過 remove(key) 方法可以刪除元素
>>> s = {1, 2, 3, 4}
>>> s.remove(4)
>>> s
{1, 2, 3}
4. 兩個set可以做數學意義上的交集、并集等操作
>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s1 & s2
{2, 3}
>>> s1 | s2
{1, 2, 3, 4}
四. 練習
給定一個只包含正整數且非空的數組,返回該數組中重復次數最多的前N個數字(返回結果按重復次數從多到少降序排列,N不存在取值非法的情況)
a=[1,6,7,4,4,5,4,5,4,5,5,6,7,8,5,6,7,3,4,2,2,1,4,8,9,4,5,6]
def get_datas(a):
result = []
data_dict = {}
#鍵值對:鍵——數字,值——在列表中的次數
#set(a)將列表轉化為set類型,并過濾掉其中重復的數字
for item in set(a):
data_dict[item] = a.count(item)
#將鍵值對按值(數字出現的次數)排序——從高到低排序
#sorted為臨時性排序,不會改變原列表data_dict的順序
res = sorted(data_dict.values(), reverse=True)
for num in res:
for key, value in data_dict.items():
#key not in result能保證相同的數字只添加一次
if num == value and key not in result:
result.append(key)
return result
result = get_datas(a)
print(result)
運行結果
[4, 5, 6, 7, 1, 2, 8, 3, 9]
原文鏈接:https://blog.csdn.net/qdPython/article/details/125319162
相關推薦
- 2022-04-25 Pandas?中的join函數應用實現刪除多余的空行_python
- 2022-06-29 tomcat正常啟動但網頁卻無法訪問的幾種解決方法_Tomcat
- 2022-07-28 C++超詳細講解逗號操作符_C 語言
- 2022-05-03 python實現跨進程(跨py文件)通信示例_python
- 2022-08-26 C++中Boost的智能指針scoped_ptr_C 語言
- 2022-10-04 基于WPF實現帶蒙版的MessageBox消息提示框_C#教程
- 2022-11-17 python實現excel轉置問題詳解_python
- 2022-05-26 Flutter?GridView顯示隨機單詞效果_Android
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支