python列表中数字排序_如何在Python中手动对数字列表进行排序?

1586010002-jmsa.png

Specs: Ubuntu 13.04, Python 3.3.1

Background: total beginner to Python, came across this "manual sorting" problem.

What I was asked to do: "Have the user enter 3 numeric values and store them in 3 different variables. Without using lists or sorting algorithms, manually sort these 3 numbers from smallest to largest."

What I was able to come up with:

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)

So my question is:

I realize that my solution is extremely limited. First it can only process 3 single digit numbers since once the input string is converted into a list, there is no way to break all digits correctly into individual numbers the user intended. Second,by using this solution, the coder is forced to enumerates all possible scenarios for the 3 numbers to compare with each other, which could be very inflexible if say, the script were to be changed to accepting user input of 100+ numbers.

If you could share some guidance regarding the question above, or regarding how to solve this problem in a different way, I'll be very greatful! Thank you.

解决方案

For three items, you could use max and min to sort them:

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)

If you don't want to use a sorting algorithm but can use lists, you could just pop out the smallest item each time and store it in a new list:

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)

It's pretty inefficient, but it works.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值