作者ntit5566 (ntit5566)
看板Python
標題[問題] list的問題請教
時間Tue Oct 29 10:31:57 2019
目前才剛剛自學python,有一個關於陣列的問題,程式碼如下
num_list = [n for n in range(1, 11)]
num_list3 = []
for item in num_list:
num_list3.insert(0, item)
print(num_list3)
-----輸出結果
[10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
想問的是為什麼輸出結果不是
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
不太懂num_list3.insert(0, item)的用法
麻煩版上的學長指點一下,謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.69.224.210 (臺灣)
※ 文章網址: https://webptt.com/m.aspx?n=bbs/Python/M.1572316319.A.962.html
2F:推 charlie11438: 這樣分解看會比較清楚。insert的用法是在索引的位置 10/29 11:38
3F:→ charlie11438: 塞入值,所以insert(0,10)將會在索引為0的位置插入1 10/29 11:38
4F:→ charlie11438: 0。所以當原po的迴圈在執行時,會一直往0的位置塞, 10/29 11:38
5F:→ charlie11438: 其他的會被擠到後面,才會呈現倒序的狀況 10/29 11:38
6F:→ penut85420: 改成 num3_list.append(item) 就會是往後面加了 10/29 12:00
8F:→ lixiaolong: 如同1樓查理大所說 如果item那個迴圈每跑一圈印一次 10/29 12:08
9F:→ lixiaolong: 的話 原po的原碼會跑出這樣的結果 10/29 12:08
10F:→ ntit5566: 瞭解,感謝兩位學長的答覆 10/29 12:11
11F:推 moodoa3583: .insert (位置,值),這是insert的用法,因為你的位置 10/29 12:16
12F:→ moodoa3583: 是0,所以新加進來的數就都會被加到list3的第一個位置 10/29 12:16
13F:→ moodoa3583: ,輸出結果就會是最後加進來的數在最前面。 10/29 12:16
14F:→ moodoa3583: 如果要照輸入順序加入的話如同樓上所說就用.append() 10/29 12:16
16F:→ wargods8402: ython-lists.html 10/29 12:26
17F:→ wargods8402: 如果想知道運作過程 可以像樓上大大 寫個迴圈印出過 10/29 12:27
18F:→ wargods8402: 程 10/29 12:27
19F:推 UCCUplz: 推個 10/31 13:37