如何在Python中手动排序数字列表?

2024-04-24 16:38:29 发布

您现在位置:Python中文网/ 问答频道 /正文

规格:Ubuntu 13.04,Python 3.3.1

背景:Python的初学者,遇到了这个“手动排序”的问题。

我被要求做的是:“让用户输入3个数值并将它们存储在3个不同的变量中。不使用列表或排序算法,手动将这3个数字从最小值排序到最大值。”

我能想到的是:

number = input("Please enter 3 numbers: ")
number = list(number)

a = int(number[0])
b = int(number[1])
c = int(number[2])

new_l = []

if a > b and a > c:
    new_l.append(a)
    if b > c:
        new_l.append(b)
        new_l.append(c)
    else:
        new_l.append(c)
        new_l.append(b)
    print(new_l)

if b > a and b > c:
    new_l.append(b)
    if a > c:
        new_l.append(a)
        new_l.append(c)
    else:
        new_l.append(c)
        new_l.append(a)
    print(new_l)

if c > a and c > b:
    new_l.append(c)
    if a > b:
        new_l.append(a)
    else:
        new_l.append(b)
        new_l.append(a)
    print(new_l)

所以我的问题是: 我意识到我的解决方案非常有限。首先,它只能处理3个单个数字,因为一旦输入字符串被转换成一个列表,就无法将所有数字正确地分解成用户想要的单个数字。第二,通过使用这个解决方案,编码器被迫枚举3个数字相互比较的所有可能场景,这可能非常不灵活,如果说,脚本将被更改为接受用户输入的100多个数字。

如果你能分享一些关于上述问题的指导,或者关于如何以不同的方式解决这个问题,我会非常高兴!谢谢您。


Tags: and用户number列表newif排序数字
2条回答

对于三个项目,可以使用maxmin对它们进行排序:

a, b, c = 3, 1, 8

x = min(a, b, c)  # Smallest of the three
z = max(a, b, c)  # Largest of the three
y = (a + b + c) - (x + z)  # Since you have two of the three, you can solve for
                           # the third

print(a, b, c)
print(x, y, z)

如果您不想使用排序算法,但可以使用列表,则可以每次弹出最小的项目并将其存储在新列表中:

numbers = [1, 8, 9, 6, 2, 3, 1, 4, 5]
output = []

while numbers:
    smallest = min(numbers)
    index = numbers.index(smallest)
    output.append(numbers.pop(index))

print(output)

虽然效率很低,但很管用。

使用气泡排序算法:

num1=input("Enter a number: ")
num2=input("Enter another number: ")
num3=input("One more! ")
if num1<num2:
    temp=0
    temp=num1
    num1=num2
    num2=temp
if num1<num3:
    temp=0
    temp=num1
    num1=num3
    num3=temp
if num2<num3:
    temp=0
    temp=num2
    num2=num3
    num3=temp
print num3, num2, num1

相关问题 更多 >