Reputation: 57
I have a list like this
Test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
I want to append reversed elements in each tuple (I might be using wrong language)
Here is the example
I want to append this
(5.0, 3.0), (7.0, 1.0), (4.0, 1.0)
If possible I don't want to append duplicates in the list
I tried this
Test.append(Test[i][1]),(Test[i][0]) # (where i = 0 to 1)
but failed
Upvotes: 0
Views: 167
Reputation: 1852
>>> Test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
>>> T = [(i[1], i[0]) for i in Test]
>>> T
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0)]
Upvotes: 0
Reputation: 5384
Didn't quite follow what you meant with i
though. But a simple list comprehension will work
myList = [(5.0, 3.0), (7.0, 1.0), (4.0, 3.0), (3.0, 5.0)]
myList.extend([(y, x) for x, y in myList if (y, x) not in myList])
Or just use a normal for-loop. You can either append to the same list, or add items to new list and then extend. I personally prefer new list and then extend as otherwise you will end up iterating over the newly appended items (which makes no difference aside from efficiency)
myList = [(5.0, 3.0), (7.0, 1.0), (4.0, 3.0), (3.0, 4.0)]
res = []
for x, y in myList:
if (y, x) not in myList and (y, x) not in res:
res.append((y, x))
myList.extend(res)
#Output
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0), (3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
Upvotes: 2
Reputation: 239483
To reverse the elements in the list, you can simply use reversed
function, and recreate the list, like this
>>> test = [(3.0, 5.0), (1.0, 7.0), (3.0, 4.0)]
>>> [tuple(reversed(item)) for item in test]
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0)]
If possible I don't want to append duplicates in the list
As you want to remove the duplicates as well, the best option would be to use collections.OrderedDict
like this
>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(tuple(reversed(item)) for item in test).keys())
[(5.0, 3.0), (7.0, 1.0), (4.0, 3.0)]
Upvotes: 1