看板 Python 關於我們 聯絡資訊
最近在用python 練leetcode 其中一題是做reverseList 參考討論區 答案如下: Q:Reverse a singly linked list. def reverseList(self, head): rev = None while head: head.next,rev,head = rev,head,head.next return rev 第四行,如果改成如下就會 Error 'NoneType' object has no attribute 'next' head,rev,head.next = head.next,head,rev 請問multiple assignment 有順序嗎?自己認為他是把右方先都存在暫時變數, 再存到左邊,如果是這樣順序怎麼變都應該沒關係. 但顯然不是. 另外請問前輩你們推薦這種寫法嗎?還是說分開一行一行的比較好 先謝謝回答 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 110.174.49.248 ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1475027232.A.4E7.html
icbruce: 明白了,右邊沒有順序,但左邊會先處理第一個再接下去 09/28 09:58
icbruce: 所以head.next 要先取代,再來才是head. 反之則會error 09/28 09:59
Typebrook: 長知識了,不過為什麼不用slice?(list[::-1]) 09/28 12:54
eight0: 那如果在右邊加括弧呢?感覺會先建成一個 tuple 再拆開 09/29 06:08
icbruce: 回Type: head是ListNode 不是list, 但我也沒發現還有這招 09/29 19:18
Typebrook: 謝謝指教,我還是coding新手沒有linked list的概念, 09/30 12:56
Typebrook: 補充了一下背景知識,的確應該和__getitem__沒什麼關聯 09/30 12:58
icbruce: 回eight, 加括弧和不加是一樣的結果,我猜他都會先建 09/30 21:42
icbruce: tuple 再分配的. 09/30 21:42