Python 程序反转元组

编写一个 Python 程序来反转元组中的项,将其元素从后往前重新排列。有多种方法可以反转元组,最突出的方法是使用内置的 reversed() 函数或切片技术。但是,您也可以使用 for 循环或任何其他迭代器来实现结果。

使用切片的 Python 程序反转元组项

在此示例中,我们使用了带有负步长值的元组切片来反转数字、字符串、混合和嵌套元组。这里,‘[::-1]’ 表示没有开始和停止值(读取所有值),但有负步长值。它指示 Python 从最后一项开始,向后移动一步,直到到达第一项。

intRTuple = (10, 30, 19, 70, 40, 60)
print("Original Tuple Items = ", intRTuple)

revIntTuple = intRTuple[::-1]
print("Tuple Items after Reversing = ", revIntTuple)

strRTuple = ('apple', 'Mango', 'kiwi')
print("String Tuple Items = ", strRTuple)

revStrTuple = strRTuple[::-1]
print("String Tuple after Reversing = ", revStrTuple)

mixRTuple = ('Apple', 22, 'Kiwi', 45.6, (1, 3, 7), 16, [1, 2])
print("Mixed Tuple Items = ", mixRTuple)

revMixTuple = mixRTuple[::-1]
print("Mixed Tuple after Reversing = ", revMixTuple)
Reverse integer and string Tuple

使用 reversed() 函数

在此程序中,我们使用了 reversed 函数来反转元组。reversed 函数 (reversed(intRTuple)) 返回反转的对象,因此我们必须将其转换回元组。

intRTuple = (3, 78, 44, 67, 34, 11, 19)
print("Original Tuple Items = ", intRTuple)

revTuple = reversed(intRTuple)
print("Data Type = ", type(revTuple))

revIntTuple = tuple(revTuple)
print("Tuple Items after Reversing = ", revIntTuple)
print("Tuple Data Type = ", type(revIntTuple))
Original Tuple Items =  (3, 78, 44, 67, 34, 11, 19)
Data Type =  <class 'reversed'>
Tuple Items after Reversing =  (19, 11, 34, 67, 44, 78, 3)
Tuple Data Type =  <class 'tuple'>

使用 For 循环反转元组的 Python 程序

在此 示例 中,for 循环 结合 reversed 函数从后往前迭代元组项。在循环中,我们将每个元组项添加到 revIntTuple。请记住,元组是不可变的,因此它们不会更改原始元组;而是创建新元组。

intRTuple = (10, 19, 29, 39, 55, 60, 90, 180)
print("Original = ", intRTuple)

revintTuple = ()

for i in reversed(range(len(intRTuple))):
    revintTuple += (intRTuple[i],)

print("After = ", revintTuple)
Original =  (10, 19, 29, 39, 55, 60, 90, 180)
After =  (180, 90, 60, 55, 39, 29, 19, 10)

在这里,我们使用了 for 循环范围 (for i in range(len(intRTuple) – 1, 0, -1)) 从后往前迭代元组项,并将它们添加到反转的 元组 中。

intRTuple = (10, 19, 29, 39, 55, 60, 90, 180)
print("Original Tuple Items = ", intRTuple)

revintTuple = ()

for i in range(len(intRTuple) - 1, 0, -1):
    revintTuple += (intRTuple[i],)

print("After Reversing the Tuple = ", revintTuple)
Program to Reverse a Tuple Example