早教吧 育儿知识 作业答案 考试题库 百科 知识分享

Python怎么除去list中的重复值?以下是不正确的,结果是[1,1,2,3,4,4,5],为什么?a=[1,1,1,1,2,3,3,3,4,4,4,4,5,5]defune(lst):foriinlst:iflst.count(i)>1:lst.remove(i)printlstune(a)谢谢大家,尤其

题目详情
Python 怎么除去list中的重复值?以下是不正确的,结果是[1, 1, 2, 3, 4, 4, 5],为什么?
a=[1,1,1,1,2,3,3,3,4,4,4,4,5,5]
def une(lst):
for i in lst:
if lst.count(i) > 1:
lst.remove(i)
print lst
une(a)
谢谢大家,尤其是1楼,写了这么多。
找到个正确答案:
def une(lst):
lst.sort()
last=lst[-1]
for i in range(len(lst)-2,-1,-1):
if lst.count(lst[i])> 1:
del lst[i]
print lst
▼优质解答
答案和解析
需要执行两次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不用我教了吧