我想實現插入排序,其中用戶輸入的數字自動按升序排列在列表中。到目前為止,我已經通過將它與列表中將被附加到的最后一個元素進行比較來完成此操作。我如何將它與整個列表進行比較以將其放置在適當的位置?我正在使用 Python 3。list = [25,3,14,17,36] a = int(input("enter")) list.append(a)for n in list: if a < n: list = [a,n] print(list) >> [8, 36]我怎樣才能輸出列表的其余部分?
2 回答

慕工程0101907
TA貢獻1887條經驗 獲得超5個贊
你只需要簡單的排序list.sort(),
我在上面添加了你的代碼。
me@me:/py$ python3
Python 3.5.2 (default, Nov 12 2018, 13:43:14)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> a = int(input("enter"))
enter8
>>> a
8
>>> list = [25,3,14,17,36]
>>> list.append(a)
>>> list
[25, 3, 14, 17, 36, 8]
>>> list.sort()
>>> list
[3, 8, 14, 17, 25, 36]
>>>
添加回答
舉報
0/150
提交
取消