用Python程序实现:近两年偶像选秀节目风靡,吸引了许多喜欢唱跳、有明星梦想的少男少女参加。《青春有你》正是节目之一。《青春有你》采用计票机制,选手获得的票数越多,排名就越靠前。本案例要求编写程序,随机接收选手的姓名和票数(存储在字典中),输出排序后的成绩。
时间: 2024-04-26 07:03:49 浏览: 177
可以通过Python中的字典和sorted函数实现选手成绩的排序。以下是示例代码:
```python
import random
# 生成随机选手和票数
players = {}
for i in range(10):
name = 'Player{}'.format(i+1)
score = random.randint(100, 1000)
players[name] = score
# 输出原始成绩
print('原始成绩:')
for name, score in players.items():
print('{}: {}'.format(name, score))
# 排序并输出成绩
sorted_players = sorted(players.items(), key=lambda x: x[1], reverse=True)
print('排序后成绩:')
for name, score in sorted_players:
print('{}: {}'.format(name, score))
```
运行结果类似如下:
```
原始成绩:
Player1: 855
Player2: 201
Player3: 365
Player4: 701
Player5: 521
Player6: 954
Player7: 442
Player8: 228
Player9: 845
Player10: 983
排序后成绩:
Player10: 983
Player6: 954
Player1: 855
Player9: 845
Player4: 701
Player5: 521
Player7: 442
Player3: 365
Player2: 201
Player8: 228
```
阅读全文