简体   繁体   中英

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 results onto a matrix. What I want is to find the inverse of the array so [(150,126),(154,124),(145,123),(149,123)] and then do another imshow .

How can I inverse the array so it achieves what I want to do?

>>> 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)]
>>>

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.

array = [(126,150),(124,154),(123,145),(123,149)]
inversed = [(item[1],item[0]) for item in array]

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