简体   繁体   中英

How do you change a specific element of a set?

In this code, I am trying to compare the value of a set that has been looped each time to a value passed (in this case a) in a parameter. What's interesting though is that it shows when I use a for each loop that each element is an integer. How do I get a integer to integer comparison without a console error?

def remove(s,a,b):
    c=set()
    c=s
    for element in c:
        element=int(element)
        if(element<a or element>b):
            c.discard(element)
    return c

def main():
    remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

main()

Output:

    if(element<=a or element>=b):
TypeError: '>=' not supported between instances of 'int' and 'set'

You reassign your local variable b :

def remove(s,a,b):
    b=set()  # now b is no longer the b you pass in, but an empty set
    b=s  # now it is the set s that you passed as an argument
    # ...    
    if(... element > b): # so the comparison must fail: int > set ??

Short implementation using a set comprehension:

def remove(s, a, b):
    return {x for x in s if a <= x <= b}

>>> remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)
{9, 2, 3, 4}

if you want int to int compare then make b as list of s.

def remove(s,a,b):
    b = list(s)
    for element in s:
        element=int(element)      
        if(element< a or element > b):
            b.remove(element)
    return b

def main():
    remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

main()

Come on, why don't we make the code shorter?

Try this:

def remove(s, a, b):
    return s.difference(filter(lambda x: not int(a) < int(x) < int(b), s))


def main():
    new_set = remove({3, 17, -1, 4, 9, 2, 14}, 1, 10)

    # {2, 3, 4, 9}
    print(new_set)


main()

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