I'm trying to reverse a tuple in different ways. Can i change the order in way (bond,james,number). I know how to change it if there are only 2 elements in tuple but how to do it when I have 3 and more? I got (number,bond,james) but how to do it in different ways, not just reversing. My code:
def change(lst):
list2 = [t[::-1] for t in lst]
list2.reverse()
return list2
print(change([("James", "Bond", "300184"),("Harry", "Prince", "111000")]))
CodePudding user response:
If you want to reverse the first two elements we can leverage on tuple unpacking in for loop.
lst = [("James", "Bond", "300184"),("Harry", "Prince", "111000")]
out = [(sec, fir, *rem) for fir, sec, *rem in lst]
print(out)
# [('Bond', 'James', '300184'), ('Prince', 'Harry', '111000')]
This solution would reverse each tuple in list as below:
(a, b, c...z) --> (b, a, c...z)
c...z
can be 0 or more elements.
CodePudding user response:
You can create a tuple as you want like below:
(get two first elements and reverse them then add others last elements at the end of each tuple)
def changing(lst):
return [(*l[:2][::-1] , *l[2:]) for l in lst]
lst = [("James", "Bond", "300184", "111000", "300184"),
("Harry", "Prince", "111000", "300184")]
result = changing(lst)
print(result)
Output:
[('Bond', 'James', '300184', '111000', '300184'),
('Prince', 'Harry', '111000', '300184')]
CodePudding user response:
You can get all possible combinations of a tuple using itertools permutation:
from itertools import permutations
list1 = [("James", "Bond", "300184"), ("Harry", "Prince", "111000")]
for tup in list1:
possible_combinations = permutations(tup)
print(tuple(possible_combinations))
Output:
(('James', 'Bond', '300184'), ('James', '300184', 'Bond'), ('Bond', 'James', '300184'), ('Bond', '300184', 'James'), ('300184', 'James', 'Bond'), ('300184', 'Bond', 'James'))
(('Harry', 'Prince', '111000'), ('Harry', '111000', 'Prince'), ('Prince', 'Harry', '111000'), ('Prince', '111000', 'Harry'), ('111000', 'Harry', 'Prince'), ('111000', 'Prince', 'Harry'))