[英]how do I sort list in python
I input like this -> 10 79 8 51 2我这样输入 -> 10 79 8 51 2
and I want to get [2, 8, 10, 51, 79]
我想得到
[2, 8, 10, 51, 79]
but I get [10, 2, 51, 79, 8]
但我得到
[10, 2, 51, 79, 8]
please tell me what's wrong with my code?请告诉我我的代码有什么问题?
python 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.如果您将输入更改为
list = [10, 79, 8, 51, 2]
,您将得到您想要的结果。 (Asides from that, it's better not to use names like list
.) (除此之外,最好不要使用
list
类的list
。)
There are three problems with your code.您的代码存在三个问题。
for i in range(0, len(list)):
for j in range(i+1, len(list)):
list[i]
to int(list[i])
.list[i]
引用更改为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:或者,更简洁地说,正如 Stef 提到的:
list = [int(x) for x in list]
This converts every item in list
to an integer instead of a string.这会将
list
中的每个项目转换为整数而不是字符串。
list
something like lst
instead.list
类似于lst
。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]输入: 10 79 8 51 2和输出: [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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.