--- title: Python WTF description: Python 到底是怎樣RRRRR tags: python lang: zh_tw --- # Python WTF [TOC] ## 這筆記存在的目的 紀錄一下我所看到 python 一些不這麼直覺的語法、行為 天啊這到底是三小 ## lambda ### WTF lambda 1 ```python print((lambda x: x(x))(lambda f: 1)) # 輸出為 1 ``` #### 解釋 拆成這樣比較好理解 ```python l1 = lambda x: x(x) l2 = lambda f: 1 print(l1(l2)) ``` 寫成 C 長這樣 ```c int l1(void (*x)()) { return (*x)(x); } int l2(void *f) { return 1; } print(l1(l2)); ``` 將 l2 這個 function pointer 帶到 l1 後 l1 裡面執行 return l2(&l2) l2 裡面執行 return 1 回傳 l2(&l2) 結果為 1,l1 return 1 **WTF :** ★★★☆☆☆☆☆☆☆ ### WTF lambda 2 ```python print((lambda z: lambda y: lambda x: z + x + y)(1)(2)(3)) # 輸出為 6 ``` #### 解釋 TBD. ## Closure ```python def outer(): x = 10 def inner(): print(x) inner() x = 20 return inner print(outer()) print('------') print(outer()()) ``` **output :** ```shell 10 <function inner at 0x7f4c6c6fa398> ------ 10 20 None ``` #### 解釋 `print(outer())` 中先執行了 outer() `outer()` 中執行 x = 10,並呼叫 inner() `inner()` 輸出 x,也就是 10 回到 `outer()` 執行 x = 20,並 return inner 最終 `print()` 印出 inner,inner 是一個 function 位置在記憶體位置 0x7f4c6c6fa398 `print(outer()())` 前面一樣 差別在 `outer()` return inner 後 又在呼叫了這個 inner 一次 `inner()` 輸出 x,這次是 20 最後什麼也沒 return,所以 `print()` 印出 None **WTF :** ★★★☆☆☆☆☆☆☆ ## tuple ```python a = ('c',) * 2 print a ``` **output** ```shell ('c', 'c') ``` ## list ```python a = ['c'] * 2 print a ``` **output** ```shell ['c', 'c'] ``` ## zip iter combo ```python code = 'abcdefgh' a = (iter(code), ) * 2 for i in zip(*a): print i ``` **output** ```shell ('a', 'b') ('c', 'd') ('e', 'f') ('g', 'h') ``` ## References - [Python的匿名函数——lambda](https://zhuanlan.zhihu.com/p/27607704) - [lambda 運算式](https://openhome.cc/Gossip/Python/LambdaExpression.html) - [Python Closures](https://www.programiz.com/python-programming/closure)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up