Home > Software engineering >  keep random list elements and remove the others
keep random list elements and remove the others

Time:04-30

I have a larg list of elements:

list= [a1, b, c, b, c, d, a2, c,...a3........]

And i want to remove a specific elements from it a1, a2, a3 suppose that i can get the indexes of the elements start with a

a_indexes = [0,6, ...]

Now, i want to remove most of these elements start with a a but not all of them, i want to keep 20 of them chosen arbitrary. How can i do so ?

I know that to remove an elements from a list list_ can use:

list_.remove(list[element position])

But i am not sure how to play with the a list.

CodePudding user response:

Here's a an approach that will work if I understand the question correctly.

We have a list containing numerous items. We want to remove some elements that match a certain criterion - but not all.

So:

from random import sample
li = ['a','b','a','b','a','b','a']
dc = 'a'
keep = 1 # this is how many we want to keep in the list

if (k := li.count(dc) - keep) > 0: # sanity check
    il = [i for i, v in enumerate(li) if v == dc]
    for i in sorted(sample(il, k), reverse=True):
        li.pop(i)

print(li)

Note how the sample is sorted. This is important because we're popping elements. If we do that in no particular order then we could end up removing the wrong elements.

An example of output might be:

['b', 'b', 'a', 'b']

CodePudding user response:

Suppose you have this list:

li=['d', 'a', 'c', 'a', 'g', 'b', 'f', 'a', 'c', 'g', 'e', 'f', 'e', 'g', 'b', 'b', 'c', 'e', 'a', 'd', 'g', 'd', 'd', 'a', 'c', 'e', 'a', 'c', 'f', 'a', 'b', 'a', 'a', 'f', 'b', 'd', 'd', 'b', 'f', 'a', 'd', 'g', 'd', 'b', 'e']

You can define a character to delete and a count k of how many to delete:

delete='a'
k=3

Then use random.shuffle to generate a random group of k indices to delete:

idx=[i for i,c in enumerate(li) if c==delete]
random.shuffle(idx)
idx=idx[:k]
>>> idx
[3, 7, 31]

Then delete those indices:

new_li=[e for i,e in enumerate(li) if i not in idx]
  • Related