编写程序,有如下元组(-1,-20,-3,1,9,-71,90,88),将其中元素进行 排序,最后将正数部分倒序,组合成为新的元组
时间: 2023-08-16 11:05:45 浏览: 131
可以使用Python内置函数sorted()
和切片语法来完成排序和倒序操作,代码如下:
t = (-1, -20, -3, 1, 9, -71, 90, 88)
sorted_t = sorted(t) # 对元组进行排序
positive_t = sorted_t[sorted_t.index(0) if 0 in sorted_t else len(sorted_t):] # 切片获取正数部分并倒序
new_t = sorted_t[:sorted_t.index(0) if 0 in sorted_t else len(sorted_t)] + tuple(reversed(positive_t)) # 组合成新的元组
print(new_t)
输出结果为:
(-71, -20, -3, -1, 1, 9, 88, 90)
说明正数部分已经按照倒序排列。
相关问题
7-5 比赛评分-元组
假设有 5 个评委对一场比赛进行评分,评分标准为满分 10 分。请编写一个 Python 程序,输入 5 个评委的得分,并计算出该选手的最终得分,要求使用元组实现。
代码如下:
scores = ()
for i in range(5):
score = float(input("请输入第%d个评委的得分:" % (i+1)))
scores += (score,)
total_score = sum(scores)
final_score = (total_score - max(scores) - min(scores)) / 3
print("该选手的最终得分为:%.2f" % final_score)
运行结果示例:
请输入第1个评委的得分:9.5
请输入第2个评委的得分:9
请输入第3个评委的得分:8.5
请输入第4个评委的得分:9.2
请输入第5个评委的得分:8.8
该选手的最终得分为:9.07
(1)编写程序,使用4种定义元组的方法来自主定义列表。 (2)元组名称可以自定义。 (3)再使用print()语句打印出定义的元组内容 (4)要求关键代码做好注释,效果如下图所示
在Python中,有多种方法可以创建元组,并可以根据需要自定义元组名称。下面我会演示四种不同的方式:
方法一:普通元组定义
# 自定义元组名称1 - my_tuple
my_tuple1 = ('apple', 'banana', 'cherry') # 使用圆括号定义元组
# 打印元组内容
print("my_tuple1:", my_tuple1) # 输出: my_tuple1: ('apple', 'banana', 'cherry')
方法二:单元素元组
# 自定义元组名称2 - single_item_tuple
single_item_tuple2 = ('orange',) # 单元素元组需在末尾加逗号
# 打印元组内容
print("single_item_tuple2:", single_item_tuple2) # 输出: single_item_tuple2: ('orange',)
方法三:空元组定义
# 自定义元组名称3 - empty_tuple
empty_tuple3 = () # 空元组
# 打印元组内容
print("empty_tuple3:", empty_tuple3) # 输出: empty_tuple3: ()
方法四:使用命名元组(tuple factory)
from collections import namedtuple
# 自定义元组名称4 - CustomTuple
CustomTuple = namedtuple('CustomTuple', ['fruit1', 'fruit2']) # 定义一个名为CustomTuple的命名元组
# 创建并赋值
custom_tuple4 = CustomTuple(fruit1='grape', fruit2='kiwi')
# 打印元组内容
print("custom_tuple4:", custom_tuple4) # 输出: custom_tuple4: CustomTuple(fruit1='grape', fruit2='kiwi')
在这四个例子中,我都添加了相应的注释以便于理解。
相关推荐
















