① python刪除list重復元素
在Python中主要有5種方式 。
1、使用set函數
set是定義集合的,無序,非重復
numList = [1,1,2,3,4,5,4]
print(list(set(numList)))
#[1, 2, 3, 4, 5]
2、先把list重新排序,然後從list的最後開始掃描
a = [1, 2, 4, 2, 4, 5,]
a.sort()
last = a[-1]
for i in range(len(a) - 2, -1, -1):
if last == a[i]:
del a[i]
else:
last = a[i]
print(a) #[1, 2, 4, 5]
3、使用字典函數
a=[1,2,4,2,4,]
b={}
b=b.fromkeys(a)
c=list(b.keys())
print(c) #[1, 2, 4]
4、append方式
def delList(L):
L1 = []
for i in L:
if i not in L1:
L1.append(i)
return L1
print(delList([1, 2, 2, 3, 3, 4, 5])) #[1, 2, 3, 4, 5]
5、count + remove方式
def delList(L):
for i in L:
if L.count(i) != 1:
for x in range((L.count(i) - 1)):
L.remove(i)
return L
print(delList([1, 2, 2, 3, 3, 4]))#[1, 2, 3, 4]
② Python 怎麼除去list中的重復值以下是不正確的,結果是[1, 1, 2, 3, 4, 4, 5],為什麼
需要執行兩次une(a)才能去除
改了一下代碼,自己跑一下下面的兩端代碼就應該知道為什麼了,效果是一樣的
>>>a=[1,1,1,1,2,3,3,3,4,4,4,4,5,5]
>>>def une(lst):
for i in lst:
print 'i=',i
print 'count('+str(i)+')='+str(lst.count(i))
if lst.count(i) > 1:
lst.remove(i)
print 'a=',a
print '-----------------------------------------'
>>>une(a)
>>>a=[1,1,1,1,2,3,3,3,4,4,4,4,5,5]
>>>def une(lst):
num = len(lst)
n=0
for n in range(num):
#print 'n=',n
i = lst[n]
print 'i=',i
print 'count('+str(i)+')='+str(lst.count(i))
if lst.count(i) > 1:
lst.remove(i)
print 'a=',a
print '-----------------------------------------'
>>>une(a)
怎麼改une不用我教了吧
③ Python列表去重的六種方法
探索Python列表去重的六種高效策略</
方法一:利用set的獨特性質</
Python內置的set數據結構具有無序且不允許重復元素的特性,我們可以巧妙地利用這個特性來去重。通過將列表轉換為set,再轉換回list,即可實現去重,盡管set會打亂原有順序,但這是唯一可能丟失順序的方法</。
方法二:藉助字典的鍵值對</
利用字典的fromkeys()函數,將列表中的元素作為鍵,可以自動去除重復,因為字典的鍵必須是唯一的。但同樣,這種方法同樣無法保持原有的元素順序</。
方法三:常規遍歷操作</
通過遍歷列表,將每個元素檢查其在列表中是否首次出現,如果未出現則添加,這種方法保留了原始順序。代碼如下:
方法四:列表推導式</
列表推導式同樣可以簡潔地去重,同時保持元素順序:new_list = [x for i, x in enumerate(old_list) if x not in new_list[:i]]</
方法五與六:sort與sorted函數</
如果對順序要求不高,可以利用sort()或sorted()函數,它們會根據元素的默認排序規則去除重復,然後重新排序。但注意,這將改變列表的原始順序。
總結</
在Python中,根據實際需求和對順序的敏感程度,選擇合適的方法去除列表中的重復項至關重要。每種方法都有其適用場景,務必根據具體問題靈活運用。
④ python中列表如何去重
可以利用set去重
代碼如下:
#coding=utf-8
li=[1,2,3,4,2,1,3,0]#列表
li2=set(li)
print(li2)
⑤ python list找出一個元素的位置(重復元素怎麼分別找出位置)
使用list的index方法可以找到list中第一次出現該元素的位置
>>>l=['a','b','c','c','d','c']
>>>find='b'
>>>l.index(find)
1
找出出現該元素的所有位置可以使用一個簡單的表理解來實現
>>>find='c'
>>>[ifori,vinenumerate(l)ifv==find]
[2,3,5]