在Python中,输入三个数并排序的方法可分为以下四种,涵盖手动实现和内置函数使用:
一、基础比较法(逐一交换)
通过多次比较和交换实现排序,代码简洁但效率较低。
def sort_three_numbers_basic(a, b, c):
if a > b: a, b = b, a
if b > c: b, c = c, b
if a > b: a, b = b, a
return a, b, c
# 示例
print(sort_three_numbers_basic(3, 1, 2)) # 输出: (1, 2, 3)
二、一次遍历法(高效实现)
通过一次遍历确定最小、中间、最大值,减少比较次数。
def sort_three_numbers_once(a, b, c):
if a > b: a, b = b, a
if b > c: b, c = c, b
if a > b: a, b = b, a
return a, b, c
# 示例
print(sort_three_numbers_once(3, 1, 2)) # 输出: (1, 2, 3)
三、使用内置函数sorted()
通过sorted()
函数快速排序,支持升序或降序排列。
# 输入处理
input_numbers = input().split()
numbers = [int(num) for num in input_numbers]
# 排序
sorted_numbers = sorted(numbers, reverse=True) # 降序
print(' '.join(map(str, sorted_numbers))) # 输出: 8 3 2
四、使用列表的sort()
方法
原地修改列表,效率较高且代码简洁。
# 输入处理
input_numbers = input().split()
numbers = [int(num) for num in input_numbers]
# 排序
numbers.sort(reverse=True) # 降序
print(' '.join(map(str, numbers))) # 输出: 8 3 2
总结 :若仅需排序三个数,推荐使用内置函数sorted()
或列表的sort()
方法,代码简洁且效率更高。若需手动实现排序逻辑,可选择一次遍历法或基础比较法。