要从控制台对一系列数字进行排序,首先将其附加到 myList
中,并且该 myList
使用 myList.sort()
n = int(input())
count = 0
myList = []
while count < n:
i = int(input())
myList.append(i)
count += 1
myList.sort()
print(myList)
有没有一种方法可以在它被添加到列表时直接自动按正确的顺序/索引放置?如果可能,我想摆脱 sort()
函数和未排序的 myList
。
最佳答案
您可以使用 bisect.insort
插入到已排序的列表中。
>>> from bisect import insort
>>> l = []
>>> insort(l, 5)
>>> l
[5]
>>> insort(l, 1)
>>> l
[1, 5]
>>> insort(l, 2)
>>> l
[1, 2, 5]
编辑:如果您不需要在每次插入后对列表进行排序,我只需在循环后对其进行排序。
关于python - 将输入整数直接排序到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69583491/