Reputation: 45
I have a set of pairs with types (str, int). I shall find the tuples that contain specific string and then increment the corresponding integer by 1. I know how to find tuples in a set with asking whether myTuple in mySet
. But I do not know the way to handle such situations. I will appreciate any help.
Here is an example set :
from sets import Set
up = 2
down = 3
right = 1
left = 2
mySet = Set([("up",up),("down",down),("right",right),("left",left)])
Say from mySet
I want to increment the second of the pair where its first element is "up"
by 1 so I need something like
if ("up",ref) in mySet:
ref += 1
By doing this, I want to increment both the value of the original variable up
and second element of the tuple.
Upvotes: 1
Views: 172
Reputation: 195
you can use the filter method to find all entries in the set where your condition, in this case the first entry being "up" is true.
subset = list(filter(lambda x: x[0] == "up", mySet))
for entry in subset:
mySet.remove(entry)
newEntry = (entry[0],(entry[1]+1))
mySet.add(newEntry)
up +=1
you cannot use entry+=1
because tuples are non-mutable in python
Upvotes: 0
Reputation: 77
I would suggest using a dictionary for your purpose. That way, the re-assignment of the new count would be more clean and easier to interpret. For instance:
>>> my_set = { 'up': 0, 'down': 0, 'left': 0, 'right': 0 }
>>> my_set['up'] += 1
>>> my_set
{'up': 1, 'down': 0, 'left': 0, 'right': 0}
As Brian describes, tuples are non-mutable so each time you update the count it has to be created a new one with the updated count. This can then be used to replace the old tuple.
Upvotes: 1