網(wǎng)站首頁(yè) 編程語(yǔ)言 正文
請(qǐng)定義函數(shù),將列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]中的重復(fù)元素除去,寫(xiě)出至少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循環(huán)
list_2 = [10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]
def func2(list_2):
#定義一個(gè)空列表
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則添加進(jìn)去,否則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() 函數(shù)創(chuàng)建一個(gè)新字典,獲取新字典的鍵(鍵值是唯一的)
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))
運(yùn)行結(jié)果:
原文鏈接:https://www.cnblogs.com/chenyablog/p/15172766.html
相關(guān)推薦
- 2022-09-21 python中模塊導(dǎo)入模式詳解_python
- 2022-09-27 Swift超詳細(xì)講解指針_Swift
- 2022-08-17 Python?獲取今天任意時(shí)刻的時(shí)間戳的方法_python
- 2022-12-03 C++實(shí)現(xiàn)重載矩陣的部分運(yùn)算符_C 語(yǔ)言
- 2021-11-06 C語(yǔ)言?如何用堆解決Topk問(wèn)題_C 語(yǔ)言
- 2023-10-12 利用touch-action解決驗(yàn)證碼滑塊滑動(dòng)時(shí),背景跟隨一起滑動(dòng)的問(wèn)題,以及詳解touch-act
- 2022-12-06 Python中八種數(shù)據(jù)導(dǎo)入方法總結(jié)_python
- 2022-02-25 Oracle函數(shù)使索引列失效的解決辦法_oracle
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運(yùn)行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲(chǔ)小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運(yùn)算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過(guò)濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯(cuò)誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實(shí)現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡(jiǎn)單動(dòng)態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對(duì)象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊(duì)列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支