简体   繁体   中英

I want to write a function that takes a list and returns it with all duplicates removed, without creating another list or string

I have tried this, it gives the output it should give([1,3,2]), however the problem is it keeps printing the output for infinite times without stop,, is there any solutions with out changing the idea of the code.

a= [1,2,2,2,1,3,2]
def rem_dup(L):
    while len(L):
        for i in L:
            y= L.count(i)
            if y>1:
                L.remove(i)  
        print L 
rem_dup(a)

Unless the point of this function is to exercise your python skills, it sounds like you want a set . A set is like a list but does not allow duplicate values. If you want your final data structure to be a list, you could do something like this:

final_list = list(set(original_list))

One way to safely do this is to loop over the list in reverse and remove only from the back:

>>> for i in range(len(a) - 1, -1, -1):
...    if a.count(a[i]) > 1:
...       del a[i]
...
>>> a
[1, 2, 3]

But this will be polynomial time, since a.count is linear and so is del a[i] .

while len(L) will always be true as long as L had something in it to begin with

Modifying L while using it with the for loop can cause items to be skipped, so you have a bug for some inputs.

If you fix that problem, you shouldn't need the while loop.

只要中的项目a可哈希的,而且您不介意开始时其余项目的顺序不同,则可以创建中间set并就地替换原始内容。

a[:] = set(a)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM