網站首頁 編程語言 正文
請定義函數,將列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]中的重復元素除去,寫出至少3種方法。
方法一:利用集合去重
list_1=[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func1(list_1):
return list(set(list_1))
print('去重后的列表:',func1(list_1))
方法二:利用for循環
list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func2(list_2):
#定義一個空列表
mylist_2=[]
#i遍歷list_2
for i in list_2:
#如果i不在mylist_2,則添加到mylist_2
if i not in mylist_2:
mylist_2.append(i)
print(mylist_2)
print(func2(list_2))
方法三:巧用sort()排序
list_3 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func3(list_3):
result_list=[]
temp_list=sorted(list_3)
i=0
while i<len(temp_list):
#如果不在result_list則添加進去,否則i+1
if temp_list[i] not in result_list:
result_list.append(temp_list[i])
else:
i+=1
return result_list
print(func3(list_3))
方法四:巧用字典
list_4= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func4(list_4):
#fromkeys() 函數創建一個新字典,獲取新字典的鍵(鍵值是唯一的)
result_list = []
for i in {}.fromkeys(list_4).keys():
result_list.append(i)
return result_list
print(func4(list_4))
方法五:利用迭代器
import itertools
list_5= [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func5(list_5):
list_5.sort()
temp_list= itertools.groupby(list_5)
result_list=[]
for i,j in temp_list:
result_list.append(i)
return result_list
print(func5(list_5))
運行結果:
原文鏈接:https://www.cnblogs.com/chenyablog/p/15172766.html
相關推薦
- 2023-02-27 C++文件讀取的4種情況匯總_C 語言
- 2022-09-03 Pycharm中運行程序在Python?console中執行,不是直接Run問題_python
- 2022-07-21 數據庫分組查詢--GROUP BY及排序
- 2022-05-15 Qt Linux獲取bios ID作為唯一標識
- 2022-05-11 解決Spring Boot報錯Mapped Statements collection alread
- 2022-04-23 uniapp封裝本地存儲處理數據的方法和具體使用
- 2023-08-15 解決:Unexpected ‘debugger‘ statement.eslint(no-debug
- 2022-10-08 LyScript實現繞過反調試保護的示例詳解_python
- 最近更新
-
- 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同步修改后的遠程分支