Home > front end >  How to remove elements from a list that appear less than k = 2?
How to remove elements from a list that appear less than k = 2?

Time:03-08

I am trying to keep elements of a list that appear at least twice, and remove the elements that appear less than twice.

For example, my list can look like:

letters = ['a', 'a', 'b', 'b', 'b', 'c']

I want to get a list with the numbers that appear at least twice, to get the following list:

letters_appear_twice = ['a', 'b'].

But since this is part of a bigger code, I don't know exactly what my lists looks like, only that I want to keep the letters that are repeated at least twice. But for the sake of understanding, we can assume I know what the list looks like!

I have tried the following:

'''

letters = ['a', 'a', 'b', 'b', 'b', 'c']

for x in set(letters):
    if letters.count(x) > 2:
        while x in letters:
            letters.remove(x)

print(letters)

'''

But this doesn't quite work like I want it too...

Thank you in advance for any help!

CodePudding user response:

letters = ['a', 'a', 'b', 'b', 'b', 'c']

res  = []
for x in set(letters):
    if letters.count(x) >= 2:
        res.append(x)
print(res)

Prints:

['b', 'a']

CodePudding user response:

Using your code above. You can make a new list, and append to it.

    new_list = []
    for x in set(letters):
         if letters.count(x) >= 2:
             new_list.append(x)
     print(new_list)

Output

['b', 'a']

CodePudding user response:

Easier to create a new list instead of manipulating the source list

def letters_more_or_equal_to_k(letters, k):
    result = []
    for x in set(letters):
        if letters.count(x) >= k:
            result.append(x)
    result.sort()
    return result


def main():
    letters = ['a', 'a', 'b', 'b', 'b', 'c']
    k = 2
    result = letters_more_or_equal_to_k(letters, k)
    
    print(result) # prints ['a', 'b']


if __name__ == "__main__":
    main()

CodePudding user response:

If you don't mind shuffling the values, here's one possible solution:

from collections import Counter

letters = ['a', 'a', 'b', 'b', 'b', 'c']
c = Counter(letters)
to_remove = {x for x, i in c.items() if i < 2}

result = list(set(letters) - to_remove)
print(result)

Output:

['a', 'b']

You can always sort later. This solution is efficient for lists with more than ~10 unique elements.

  • Related