keep random list elements and remove the others

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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']

Method 2

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]


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x