当我尝试简单地对一些数字进行排序时,我在Python中使用此代码存在以下问题。
array = input().split(" ")
between_numbers = " <= ".join(sorted(array))
print(between_numbers)
使用此给定输入:
-100 500 36724 -673 874 37 36 324 627 82 76537 -772 -936 2467 2365 -3763
我明白了:
-100 <= -3763 <= -673 <= -772 <= -936 <= 2365 <= 2467 <= 324 <= 36 <= 36724 <= 37 <= 500 <= 627 <= 76537 <= 82 <= 874
代替此:
-3763 <= -936 <= -772 <= -673 <= -100 <= 36 <= 37 <= 82 <= 324 <= 500 <= 627 <= 874 <= 2365 <= 2467 <= 36724 <= 76537
有人可以告诉我这是为什么以及如何解决吗?
答案 0 :(得分:2)
split
为您提供了一个字符串列表。默认情况下,字符串按字典顺序进行比较:
"a" < "aardvark" < "b"
"1" < "10" < "2"
如果您有一个数字列表,或者将排序键指定为int
转换,则sorted
会做您想要的。因此,要么
array = [int(x) for x in input().split(" ")]
或
between_numbers = " <= ".join(sorted(array, key=int))
答案 1 :(得分:0)
将每个数字转换为Integer,然后进行排序
array = [int(i) for i in input.split(' ')]
您将获得根据数字而不是根据字符串排序的列表(这种情况在您的情况下发生)
答案 2 :(得分:-1)
x = np.array([2,1,4,3,5]) np.sort(x) 你可以用这个