Python|反转元组列表中的每个元组
给定一个元组列表,编写一个Python程序来反转给定元组列表中的每个元组。
例子:
Input : [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
Output : [(2, 1), (5, 4, 3), (9, 8, 7, 6)]
Input : [('a', 'b'), ('x', 'y'), ('m', 'n')]
Output : [('b', 'a'), ('y', 'x'), ('n', 'm')]
方法#1:负步切片
我们可以使用标准的负步切片tup[::-1]
来获取元组的反转,并使用列表推导来获取每个元组的反转。
# Python3 program to Reverse
# each tuple in a list of tuples
def reverseTuple(lstOfTuple):
return [tup[::-1] for tup in lstOfTuple]
# Driver code
lstOfTuple = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(reverseTuple(lstOfTuple))
输出:
[(2, 1), (5, 4, 3), (9, 8, 7, 6)]
方法 #2:使用reversed()
Python的内置reversed()
方法也可用于反转列表中的每个元组。
# Python3 program to Reverse
# each tuple in a list of tuples
def reverseTuple(lstOfTuple):
return [tuple(reversed(tup)) for tup in lstOfTuple]
# Driver code
lstOfTuple = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(reverseTuple(lstOfTuple))
输出:
[(2, 1), (5, 4, 3), (9, 8, 7, 6)]
方法 #3:使用map()
函数
Python map()函数也可以通过将负步切片映射到元组列表来达到目的。
# Python3 program to Reverse
# each tuple in a list of tuples
def reverseTuple(lstOfTuple):
return list(map(lambda tup: tup[::-1], lstOfTuple))
# Driver code
lstOfTuple = [(1, 2), (3, 4, 5), (6, 7, 8, 9)]
print(reverseTuple(lstOfTuple))
输出:
[(2, 1), (5, 4, 3), (9, 8, 7, 6)]