how to increment inside tuple in python?
Solution 1
A list comprehension will do the trick:
>>> t = [(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
>>> print [tuple((a, b+1) for a, b in group) for group in t]
[[('d', 1), ('g', 1)], [('d', 1), ('d', 2)], [('i', 1), ('g', 1)]]
Solution 2
You can't change the values in tuples, tuples are immutable. You would need to make them be lists or create a new tuple with the value you you want and store that.
Solution 3
This is the least pythonic way but the most explanatory.
Split into lists, add values to the integer list, then zip them back together:
valued = []
lettered = []
plusone = []
listed = [(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
for x,y in listed:
for subx, suby in x,y:
valued.append(int(suby))
lettered.append(subx)
for value in valued:
value = value + 1
plusone.append(int(value))
#print plusone
coolness = zip(lettered,plusone)
print coolness
exit()
The results are:
[('d', 1), ('g', 1), ('d', 1), ('d', 2), ('i', 1), ('g', 1)]
Related videos on Youtube
Palash Ahuja
Updated on September 15, 2022Comments
-
Palash Ahuja over 1 year
Suppose that I have tuples of the form
[(('d',0),('g',0)),(('d',0),('d',1)),(('i',0),('g',0))]
Then how do I increment the numbers inside the tuple that they are of the form:-
[(('d',1),('g',1)),(('d',1),('d',2)),(('i',1),('g',1))]
?
I am able to do this in a single for loop. But I am looking for shorter methods.
P.S. You are allowed to create new tuples -
Navith almost 9 yearsThe tuples are in a list according to the question.
-
Eric Renouf almost 9 years@Navith Right, but the tuples themselves still cannot be changed, it doesn't matter whether or not they are in a list
-
Palash Ahuja almost 9 yearsYou are allowed to create new tuples and store them
-
Navith almost 9 yearsBut you can change the list (through
[:] =
) to use new tuples with the second value incremented. -
Palash Ahuja almost 9 yearsPlease elaborate @Navith
-
Eric Renouf almost 9 years@Navith that's what I was trying to say, what part of it doesn't say that? you cannot change the tuples, but you can "create a new tuple with the value you want and store that" as I said
-
David Greydanus almost 9 years"I am able to do this in a single for loop. But I am looking for shorter methods." This is not shorter...
-
james-see almost 9 years@DavidGreydanus whoops, I swear that wasn't in the question at first.
-
DaHoC almost 3 yearsFor newer Python versions 3+,
print
requires parentheses:print( [tuple((a, b + 1) for a, b in group) for group in t] )