新聞中心
創(chuàng)新互聯(lián)Python教程:

成都創(chuàng)新互聯(lián)是一家專注于成都網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計與策劃設(shè)計,阜新網(wǎng)站建設(shè)哪家好?成都創(chuàng)新互聯(lián)做網(wǎng)站,專注于網(wǎng)站建設(shè)十年,網(wǎng)設(shè)計領(lǐng)域的專業(yè)建站公司;建站業(yè)務(wù)涵蓋:阜新等地區(qū)。阜新做網(wǎng)站價格咨詢:13518219792
編寫一個 Python 程序來反轉(zhuǎn)元組項。我們使用具有負值的元組切片來反轉(zhuǎn)數(shù)值、字符串、混合和嵌套元組。
# Tuple Reverse
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)
Original Tuple Items = (10, 30, 19, 70, 40, 60)
Tuple Items after Reversing = (60, 40, 70, 19, 30, 10)
String Tuple Items = ('apple', 'Mango', 'kiwi')
String Tuple after Reversing = ('kiwi', 'Mango', 'apple')
Mixed Tuple Items = ('Apple', 22, 'Kiwi', 45.6, (1, 3, 7), 16, [1, 2])
Mixed Tuple after Reversing = ([1, 2], 16, (1, 3, 7), 45.6, 'Kiwi', 22, 'Apple')在這個 python 示例中,我們使用了反轉(zhuǎn)函數(shù)來反轉(zhuǎn)元組。反轉(zhuǎn)函數(shù)(reversed(intRTuple))返回反轉(zhuǎn)的對象,所以我們必須將其轉(zhuǎn)換回 Tuple。
# Tuple Reverse
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 =
Tuple Items after Reversing = (19, 11, 34, 67, 44, 78, 3)
Tuple Data Type =
使用 For 循環(huán)反轉(zhuǎn)元組的 Python 程序
在這個 Python 示例中,帶有反轉(zhuǎn)函數(shù)的 for 循環(huán)從最后一個到第一個迭代元組項。在循環(huán)中,我們將每個元組項添加到 revIntTuple 中。
# Tuple Reverse
intRTuple = (10, 19, 29, 39, 55, 60, 90, 180)
print("Original Tuple Items = ", intRTuple)
revintTuple = ()
for i in reversed(range(len(intRTuple))):
revintTuple += (intRTuple[i],)
print("After Reversing the Tuple = ", revintTuple)
Original Tuple Items = (10, 19, 29, 39, 55, 60, 90, 180)
After Reversing the Tuple = (180, 90, 60, 55, 39, 29, 19, 10)這里,我們使用 for loop range(for I in range(len(intRTuple)–1,0,-1))從最后一個到第一個迭代元組項,并將它們相加以反轉(zhuǎn)元組。
# Tuple Reverse
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) 分享文章:Python程序:反轉(zhuǎn)元組
轉(zhuǎn)載來于:http://www.dlmjj.cn/article/djddcoe.html


咨詢
建站咨詢
