python输入数字并排序,在python中对数字进行排序

I'm trying to get a function where if you do sort(listname) it would sort all the numbers inside that list from least to greatest.

I'm not sure whats wrong with mine, but I need some help as the output isn't actually least to greatest it does least to greatest for the first two numbers of the number.

Example :

If list has 23, 212, 44 in it than I sort it the output will be like this.

Output :

212,23,44

It should be 23, 44, 212.

Code:

def sort(my_list):

size = len(my_list)

for i in range(size):

for j in range(size-i-1):

if(my_list[j] > my_list[j+1]):

tmp = my_list[j]

my_list[j] = my_list[j+1]

my_list[j+1] = tmp

More code :

numbers=([])

amount=input("How many numbers are in your list? ")

print("")

counter = 0

ran = 0

while counter < int(amount):

counter = counter + 1

ran = ran + 1

num3 = input(str(ran) + ". Input: ")

try:

val = int(num3)

except ValueError:

num3 = input(str(ran) + ". Input: ")

sort(numbers)

numbers.append(num3)

解决方案

That looks like your list doesn't contain any numbers but strings. Python doesn't try to guess what might be inside of those strings, so you get an odd sort order.

You have two options:

Convert list elements to int before comparing them (if(int(my_list[j]) > int(my_list[j+1])):)

Search this site for python natural sort to get answers how to implement "natural sorting" in Python.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值