简体   繁体   中英

How to discard multiple elements from a set?

I am trying to discard elements with length less than 10, but it doesn't work.

a = {'ab', 'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}
a.discard(x for x in a if len(x.split())<9) # discard elements with length<10
print(a)

I got this output:

{'zx c vbnmkljhgffdsa a', 'qwe r tyuio p', 'ab'}

'ab' doesn't match the condition, I don't know why it's still here?

And my desired output is:

{'zx c vbnmkljhgffdsa a', 'qwe r tyuio p'}

You need to call discard on individual items, not on the generator of items to be discarded:

for x in [x for x in a if len(x.split()) < 9]:
    a.discard(x)

Be mindful that you can't discard items while iterating through the set, so this will not work:

for x in a:
    if len(x.split()) < 9:
        a.discard(x)

Although this is beyond your question, I'd like to add that there are better ways to do what you want through set comprehension or set subtraction as suggested in another answer and comments.

You are using the wrong method to remove elements from the set. discard removes an element from the set only if it exists. You want to remove elements based on a condition, so you need to use a different approach. Here's a corrected version of the code:

a = {'ab', 'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}
a = {x for x in a if len(x.split()) >= 9}
print(a)

This code creates a new set with only the elements that meet the condition, and then assigns it back to a. The desired output is achieved:

{'z x c v b n m k l j h g f f d s a a', 'q w e r t y u i o p'}

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