題目三 刪除列表中的重復元素
1 temLst=[1,3,53,6,7,35,63,6,6,4,7,5,6,7,34] 2 n=len(temLst) 3
4 #不借助新的變量
5 #確定外層循環次數:i in range(1,n-1) index=0,index=n-1 不用比,
6 #確定內層循環次數:j in range(i+1,n-1) 且i+1 < n-1 哦
7 #比如:i=3 時,依次與后面的元素比較,相等,則pop掉
8 #注意,list是長度在變化哦 ,同時j此時不+1
9 flag=0 #但循環了45次,效率不高哦 10 for i in range(1,len(temLst)-1): 11 j=i+1
12 while j<len(temLst)-1: 13 flag=flag+1
14 if temLst[i]==temLst[j]: 15 temLst.pop(j) 16 else: 17 j=j+1
18 print(temLst,'去重復的元素') 19 print('flag循環次數:',flag)
#借助其他變量 #方法一:用內置函數 #print(list(set(temLst))) #一行代碼解決 但順序變了
temLst=[1,3,53,6,7,35,63,6,6,4,7,5,6,7,34] temSet=set(temLst) temLst2=list(temSet) temLst2.sort(key=temLst.index) #解決順序問題
print(temLst2,'temp2按key排序后:') #方法二: 遍歷去除重復(通過追加到新的lst時,先判重)
temLst=[1,3,53,6,7,35,63,6,6,4,7,5,6,7,34] List2=[] for i in temLst: #注意這里不是用i in range(n)
if not i in List2: List2.append(i) print(List2,'list2') #方法三:列表推導式
temLst=[1,3,53,6,7,35,63,6,6,4,7,5,6,7,34] List2=[] [List2.append(i) for i in temLst if not i in List2] print(List2,'列表推導式')
list.pop(index) 與list.remove(value)對比:
pop(...)
L.pop([index]) -> item -- remove and return item at index (default last).
Raises IndexError if list is empty or index is out of range.>>> help(list.remove)
Help on method_descriptor:remove(...)
L.remove(value) -> None -- remove first occurrence of value.
Raises ValueError if the value is not present.
說明:這里temLst=[1,3,53,6,7,35,63,6,6,4,7,5,6,7,34] 去重時,建議使用pop(index) 指哪打哪
因為remove(value)移除的是該列表中第一次出現的這個元素[1,3,53,6,7,35,63,6,6,4,7,5,6,7,34],若采用remove將出除紫色標記的元素,而實際期望是去除綠色標記的元素。