在python中对数字进行排序 [英] Sorting numbers in python

查看:270
本文介绍了在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.

示例:

如果列表中有23个,212个,44个,而不是我对它进行排序,则输出将是这样.

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

输出:

212,23,44

212,23,44

应为应该是23、44、212.

It should be 23, 44, 212.

代码:

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

更多代码:

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)

推荐答案

该列表似乎不包含任何数字,但包含字符串. Python不会尝试猜测这些字符串中可能包含的内容,因此您会得到一个奇怪的排序顺序.

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.

您有两个选择:

  1. 在比较它们之前将列表元素转换为int(if(int(my_list[j]) > int(my_list[j+1])):)
  2. 在此站点上搜索python natural sort,以获取有关如何在Python中实现自然排序"的答案.
  1. Convert list elements to int before comparing them (if(int(my_list[j]) > int(my_list[j+1])):)
  2. Search this site for python natural sort to get answers how to implement "natural sorting" in Python.

这篇关于在python中对数字进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆