brain storm
brain storm

Reputation: 31252

how to compare values in set and rewrite them in python

here is my code I define an empty set, I want to compare se([i]) > 0, then reassign the value of se([i]) to be 0. I am not able to do this since se([i]) is a set and cannot be compared to int. kindly help. I am new to python programming.

se =set()
se.update([8])
print (se)
for i in range (10):
    se.update([i])
    print type(se)
    print len(se)
print se

Upvotes: 0

Views: 331

Answers (1)

abarnert
abarnert

Reputation: 365807

If you're just trying to compare each element of se to 0, and replace the ones that are > 0 with 0, that's pretty easy:

se = {0 if element > 0 else element for element in se}

Or, if you think about it:

se = {min(element, 0) for element in se}

You can't do this by indexing se[i], because sets aren't indexable, because the whole point of sets (both mathematical and Python) is that they're unordered. And you definitely can't do it by calling se([i]), because you sets aren't functions, or other callable (function-like) things. If you really wanted to do it by mutating in place, you could:

for element in se.copy():
    if element > 0:
        se.remove(element)
        se.add(0)

(Notice the se.copy() there—you can't change the shape of a collection while iterating over it, so you need to iterate over a copy of it instead.)

Meanwhile, again, the whole point of a set is that it's unordered, which means adding 0 multiple times is exactly the same as adding it once. So:

>>> se = { -3, -2, -1, 0, 1, 2, 3 }
>>> print se
set([0, 1, 2, 3, -1, -3, -2])
>>> se = {min(element, 0) for element in se}
>>> print se
set([0, -2, -3, -1])

Or, using your code (with some of the extra print statements removed for brevity):

>>> se =set()
>>> se.update([8])
>>> print (se)
set([8])
>>> for i in range (10):
...     se.update([i])
>>> print se
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> se = {min(element, 0) for element in se}
>>> print se
set([0])

Upvotes: 1

Related Questions