Home > database >  How to find the location of the nth occurrence of an element in a python list
How to find the location of the nth occurrence of an element in a python list

Time:01-29

I need to create a function that takes two arguments: a list lst and a number num. If an element occurs in lst more than num times, remove the extra occurrence(s) and return the result.

So far I have:

def delete_occurrences(lst, num):
    for x in lst:
        if lst.count(x) > num:
            lst.pop(lst.index(x, lst.index(x) 1))
    return lst

However for an case such as ([1, 1, 3, 3, 7, 2, 2, 2, 2], 3) it doesn't delete the correct repetitions.

CodePudding user response:

def delete_occurrences(lst, num):
    i = 0
    while i < len(lst) :
        if lst.count(lst[i]) > num:
            lst.pop(i)
            i-=1
        i =1
    return lst

CodePudding user response:

IIUC, use list.count with a listcomp to slice the extra-occurrences :

L = [1, 1, 3, 3, 7, 2, 2, 2, 2]

def delete_occurrences(lst, num):
    return [x for i, x in enumerate(lst) if lst[:i].count(x) < num]
​

Output :

delete_occurrences(L, 3)
#[1, 1, 3, 3, 7, 2, 2, 2]

CodePudding user response:

Here's a solution that keeps your general logic, parsing the list in reverse order so as not to mess up the iteration:

def delete_occurrences(lst, num):
    for i in range(len(lst)-1,-1,-1):
        if lst.count(lst[i]) > num:
            lst.pop(i)
    return lst
  • Related