【python练习题】 删除列表中的重复元素,list的应用

题目三 删除列表中的重复元素

 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将出除紫色标记的元素,而实际期望是去除绿色标记的元素。