简体   繁体   中英

Remove Multiple Elements in a Python List Once

(Using Python 3)

Given this list named numList: [1,1,2,2,3,3,3,4]. I want to remove exactly one instance of “1” and “3” from numList. In other words, I want a function that will turn numList into: [1,2,2,3,3,4]. What function will let me remove an X number of elements from a Python list once per element I want to remove? (The elements I want to remove are guaranteed to exist in the list)

For the sake of clarity, I will give more examples:

[1,2,3,3,4] Remove 2 and 3 [1,3,4]

[3,3,3] Remove 3 [3,3]

[1,1,2,2,3,4,4,4,4] Remove 2, 3 and 4 [1,1,2,4,4,4]

I've tried doing this:

numList=[1,2,2,3,3,4,4,4]

remList = [2,3,4]

for x in remList:

 numList.remove(x)

This turns numList to [1,2,3,4,4] which is what I want. However, this has a complexity of:

O((len(numList))^(len(remList)))

This is a problem because remList and numList can have a length of 10^5. The program will take a long time to run. Is there a built-in function that does what I want faster?

Also, I would prefer the optimum function which can do this job in terms of space and time because the program needs to run in less than a second and the size of the list is large.

Your approach:

for x in rem_list:
    num_list.remove(x)

is intuitative and unless the lists are going to be very large I might do that because it is easy to read.

One alternative would be:

result = []
for x in num_list:
    if x in rem_list:
        rem_list.remove(x)
    else:
        result.append(x)

This would be O(len(rem_list) ^ len(num_list)) and faster than the first solution if len(rem_list) < len(num_list).

If rem_list was guaranteed to not contain any duplicates (as per your examples) you could use a set instead and the complexity would be O(len(num_list)).

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