新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
python如何列表去重
使用set去重
1、將列表轉(zhuǎn)換為集合,自動(dòng)去除重復(fù)元素。

創(chuàng)新互聯(lián)專注于營口企業(yè)網(wǎng)站建設(shè),自適應(yīng)網(wǎng)站建設(shè),商城系統(tǒng)網(wǎng)站開發(fā)。營口網(wǎng)站建設(shè)公司,為營口等地區(qū)提供建站服務(wù)。全流程按需規(guī)劃網(wǎng)站,專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
2、將集合轉(zhuǎn)換回列表。
示例代碼:
def remove_duplicates(lst):
return list(set(lst))
my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = remove_duplicates(my_list)
print(new_list)
使用列表推導(dǎo)式去重
1、遍歷列表,只保留第一次出現(xiàn)的元素。
示例代碼:
def remove_duplicates(lst):
return [x for i, x in enumerate(lst) if x not in lst[:i]]
my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = remove_duplicates(my_list)
print(new_list)
使用字典去重
1、將列表元素作為字典的鍵,值可以設(shè)置為任意值(如None)。
2、將字典的鍵轉(zhuǎn)換為列表。
示例代碼:
def remove_duplicates(lst):
return list(dict.fromkeys(lst).keys())
my_list = [1, 2, 2, 3, 4, 4, 5]
new_list = remove_duplicates(my_list)
print(new_list)
新聞名稱:python如何列表去重
網(wǎng)址分享:http://m.fisionsoft.com.cn/article/ccejpdh.html


咨詢
建站咨詢
