2019年10月2日 星期三

Python 數值互換如何運作

在 Python 裡,以下這段 Code 是被允許的
a = 1
b = 2
a, b = b, a  # b = 1, a = 2
其理由是 Python 會計算等號右邊的值,計算完後才將值分配到等號左邊。
可以 import dis 看其實際如何運作。
import dis

def bar(a, b, c, d):
    d, c, b, a = a, b, c, d

dis.dis(bar)
  2           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 LOAD_FAST                2 (c)
              9 LOAD_FAST                3 (d)
             12 BUILD_TUPLE              4
             15 UNPACK_SEQUENCE          4
             18 STORE_FAST               3 (d)
             21 STORE_FAST               2 (c)
             24 STORE_FAST               1 (b)
             27 STORE_FAST               0 (a)
             30 LOAD_CONST               0 (None)
             33 RETURN_VALUE    

參考資料 : stackoverflow

Related Posts:

  • Python 遞迴初學最近用 python 刷題 刷到要用 DFS 的題目,想用遞迴去寫才發現 python 沒有指標 看著討論的 python 大神寫的程式碼,發現都是 python 裡的參數都是指標 下面拿一題示範 0947 - Most Stones Removed with Same Row or Column class Solution: def removeStones(self, stones: List[L… Read More
  • Python Windows 換行符號與 Unix 換行轉換 ( convert CRLF to LF ) Convert CRLF to LF def convertCRLFtoLF(self, filename): WINDOWS_LINE_ENDING = b'\r\n' UNIX_LINE_ENDING = b'\n' with open(filename, "rb") as f: content = f.read() … Read More
  • Python bin() Python bin() bin(10) // 0b1010 type(bin(10)) // <class 'str'> bin(10)[2:] // 1010 … Read More
  • Python - sys, os.path 常見的 module 應用 Common python module - sys sys parameter 一些常見系統參數 import sys print(sys.platform) # linux sys.argv 像 c/c++ 的 argv 一樣,可以吃從 command line 傳入的參數。 # test.py 123 456 789 print (argv) … Read More
  • Python - BeautifulSoup 基本應用 (1) BeautifulSoup 紀錄下 Python 網頁爬蟲大部分會用到的 BeautifulSoup。BeautifulSoup 本質上就是 parser,知道這點後其 function 和 parameter 的使用就能得心應手。 Install 這裡紀錄使用 pip 安裝 pip install beautifulsoup4 pip install lxml # 非必要 I… Read More

0 意見:

張貼留言

Popular Posts