简体   繁体   中英

how do I sort list in python

I input like this -> 10 79 8 51 2

and I want to get [2, 8, 10, 51, 79]

but I get [10, 2, 51, 79, 8]

please tell me what's wrong with my code?

python

list = input().split()
print(list)
for i in range(0, 4):
    print(i)
    for j in range(i+1, 5):
        if list[i] > list[j]:
            print(list[i],list[j])
            list[i], list[j] = list[j], list[i]
            print(list)
        else:
            print(j, list[i], list[j])
            print("don't switch")

The logic of your sort is correct, however it's not working on what you think it is. In practice, it is working on a list of strings (not integers ), and so the comparison is lexicographic, not numeric. Under this criteria, your list is sorted.

If you would change your input to list = [10, 79, 8, 51, 2] , you'd get the result you want. (Asides from that, it's better not to use names like list .)

There are three problems with your code.

  1. Instead of iterating from 0 to 4, or i+1 to 5, do this:
for i in range(0, len(list)):
    for j in range(i+1, len(list)):
  1. As Ami Tavory pointed out, you are iterating over STRINGS of numbers, not the numbers themselves. To fix this, change every reference to list[i] to int(list[i]) . Or before the for loops, you can do this:
for i in range(0, len(list)):
    list[i] = int(list[i])

Or, even more succinctly, as Stef mentioned:

list = [int(x) for x in list]

This converts every item in list to an integer instead of a string.

  1. As Random Davis mentioned, don't name your variables after existing types in Python. Name list something like lst instead.

There is a simpler way to write your code . check this out :

a = list(map(int,input().split()[:5])) ## Enter 5 numbers with in one line with one space distance
#This method can also be used for N  numbers , you just need to change 4.

tol = len(a) 
for j in range(tol-1):       ## Helps to check sorting process again and again until all of numbers are sorted
    for i in range(tol-1):  ## To compare each number with next one
        if a[i] > a[i+1]:
            temp = a [i]
            a [i] = a[i+1]
            a [i+1]=temp
        else:
            continue
print(a)  

input : 10 79 8 51 2 and Output: [2, 8, 10, 51, 79]

Simple way to sort list is:

list1 = [10, 79, 8, 51, 2]
print(sorted(list1))

output:[2, 8, 10, 51, 79]

I dont know if that will work but i think that sort less. Try maybe to increase your number of loop. Or try this :

list = input().split()

#Turn every value of your list into int and not string
for i in range(0, len(list)): 
    list[i] = int(list[i]) 

print(list)
  
# Sorting the list
list.sort() 
  
print(list) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM