【发布时间】:2016-11-15 19:23:49
【问题描述】:
我正在尝试在 python 中对 3 个数字进行排序,而不使用内置的排序方法,例如 'sorted' 或 .sort。
假设我有数字...
2、500、25、15、12
我想输出为 2, 12, 15, 25, 500
我想模仿python内置的排序函数如何工作,但找不到它的源代码。
我做了 3 个数字:
msg = "Give me a number: "
pfix = " is the greatest"
a = int(input(msg))
b = int(input(msg))
c = int(input(msg))
nums = []
if a>b and a>c:
nums.append(a)
elif b>a and b>c:
nums.append(b)
else:
nums.append(c)
if a>b and b>c:
nums.append(b)
elif a>b and b>c:
nums.append(b)
elif a>c and c>b:
nums.append(c)
elif b>a and a>c:
nums.append(a)
elif b>c and c>a:
nums.append(c)
elif c>a and a>b:
nums.append(a)
elif c>b and b>a:
nums.append(b)
if a<b and a<c:
nums.append(a)
elif b<a and b<c:
nums.append(b)
elif c<b and c<a:
nums.append(c)
print(nums)
我知道这是一个不好的方法,因为它只适用于 3 个数字。我需要一些可以使用 for 循环处理不定数字列表的东西
喜欢...
def num_sort(_list):
for i in range(0, len(_list)):
...
并像这样使用
print(num_sort([2, 500, 25, 15, 12]))
我将如何获得特定的排序? 例如升序或降序...
我知道这就像重新发明轮子,但有人告诉我我需要自己创造方法。
你会怎么做?
提前致谢。
【问题讨论】:
-
阅读排序方法:冒泡、插入、合并、快速
-
不要粗鲁,但是,如果您被要求制作自己的方法,您为什么要问我们?你知道排序算法吗?
-
我提交了上面的代码,他们选择接受,因为无论多么糟糕,它都会按照他们的要求进行。 3个数字。我想知道应该怎么做。