创新互联Python教程:
成都创新互联是一家专注于成都网站建设、成都网站设计与策划设计,阜新网站建设哪家好?成都创新互联做网站,专注于网站建设十年,网设计领域的专业建站公司;建站业务涵盖:阜新等地区。阜新做网站价格咨询:13518219792
编写一个 Python 程序来反转元组项。我们使用具有负值的元组切片来反转数值、字符串、混合和嵌套元组。
# 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 示例中,我们使用了反转函数来反转元组。反转函数(reversed(intRTuple))返回反转的对象,所以我们必须将其转换回 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 =
在这个 Python 示例中,带有反转函数的 for 循环从最后一个到第一个迭代元组项。在循环中,我们将每个元组项添加到 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))从最后一个到第一个迭代元组项,并将它们相加以反转元组。
# 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程序:反转元组
文章起源:http://www.shufengxianlan.com/qtweb/news43/23543.html
网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等
声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联