Invert Tuples In A List Of Tuples
I have an array [(126,150),(124,154),(123,145),(123,149)](just a sample of the numbers, the array is too large to show all of them) which I have then used imshow to plot the result
Solution 1:
>>>arr = [(126,150),(124,154),(123,145),(123,149)]>>>reverseArr = [x[::-1] for x in arr]>>>reverseArr
[(150, 126), (154, 124), (145, 123), (149, 123)]
>>>
Solution 2:
If you don't mind iterators:
a = [(126,150),(124,154),(123,145),(123,149)]
inverse = map(reversed, a)
Or here are a few options if you want tuples:
inverse = map(tuple, map(reversed, a))
inverse = map(lambda x: (x[1], x[0]), a)
inverse = zip(*reversed(zip(*a)))
From a couple of quick tests I found that list comprehensions are the most efficient method for short lists and the zip method is most efficient for longer lists.
Solution 3:
array = [(126,150),(124,154),(123,145),(123,149)]
inversed = [(item[1],item[0]) for item in array]
Post a Comment for "Invert Tuples In A List Of Tuples"