The Truth of Sisyphus
  • Introduction
  • Deep Learning
    • Basics
      • Hinge Loss
      • Regularizations
      • Linear Classification
      • Multi-Class and Cross Entropy Loss
      • Batch Norm and other Normalizations
      • Optimization
      • Optimization Functions
      • Convolution im2col
      • Activation Functions
      • Derivatives
        • Derivatives of Softmax
        • A Smooth (differentiable) Max Function
      • Model Ensemble
      • Layers Python Implementation
    • Classification
      • Mobile friendly networks
      • Non-local Neural Networks
      • Squeeze-and-Excitation Networks
      • Further Attention Utilization -- Efficience & Segmentation
      • Group Norm
      • ShuffleNet V2
    • Segmentation
      • Several Instance Segmentation
      • A Peek at Semantic Segmentation
      • Design Choices for Mobile Friendly Deep Learning Models, Semantic Segmentation
      • Efficient Video Object Segmentation via Network Modulation
      • BiSeNet
      • DeepLabV3+
    • Detection
      • CornerNet
      • IoU-Net
      • Why smooth L1 is popular in BBox Regression
      • MTCNN-NCNN
      • DetNet
      • SSD Illustration
    • RNN Related
      • GRU vs LSTM
      • BERT
    • Reinforcement Learning
      • AutoML in Practice Review
      • DRL for optimal execution of profolio transaction
    • Multi-task
      • Multi-task Overview
      • What are the tricks in Multi-Task network design?
    • Neural Network Interpretation
      • Neuron Visualization
    • Deep Learning Frameworks
      • How does Caffe work
      • [Gluon] When to use (Hybrid)Sequential and (Hybrid)Block
      • Gluon Hybrid Intro
      • Gluon HybridBlocks Walk-Through
      • A quick tour of Torch internals
      • NCHW / NHWC in Pytorch
      • Static & Dynamic Computation Graph
    • Converting Between DL Frameworks
      • Things To Be Considered When Doing Model Converting
      • Caffe to TensorFlow
    • Computation Graph Optimization
      • Two ways of TensorRT to optimize Neural Network Computation Graph
      • Customized Caffe Memory Optimization
      • NCNN Memory Optimization
      • Symbolic Programs Advantages: More Efficient, Reuse Intermediate Memory, Operation Folding
    • Deep Learning Debug
      • Problems caused by dead ReLU
      • Loss jumps to 87.3365
      • Common Causes of NANs During Training
    • Deployment
      • Efficient Convolution Operation
      • Quantization
    • What I read recently
      • Know Google the Paper Way
      • ECCV 2018
      • Neural Machine Translation
      • Street View OCR Extraction System
      • Teaching Machines to Draw
      • Pixel to Graph
      • Burst Image Deblurring
      • Material for Masses
      • Learning to Separate Object Sounds by Watching Unlabeled Video
    • Papers / Posts to be read
    • Dummy thoughts
  • Machine Learning
    • Classification
    • Regression
    • Clustering
    • Dimension Reduction
    • Metrics
    • Regularization
    • Bayesian Example
    • Machine Learning System Design
    • Recommendation
    • Essentials of Machine Learning
    • Linear Regression
    • Logistic Regression
      • Logistic Function
    • Gaussian Discriminant Analysis
    • Naive Bayes
    • SVM
    • MLE vs MAP
    • Boosting
    • Frequent Questions
    • Conclusion of Machine Learning
  • Python notes
    • Python _ or __ underscores usage
    • Python Multiprocess and Threading Differences
    • Heapq vs. Q.PriorityQueue
    • Python decorator
    • Understanding Python super()
    • @ property
    • Python __all__
    • Is Python List a Linked List or Array
    • What is the "u" in u'Hello world'
    • Python "self"
    • Python object and class
    • Python Class' Instance method, Class method, and Static Methods Demystified
    • Python WTF
    • Python find first value index in a list: [list].index(val)
    • Sort tuples, and lambda usecase
    • Reverse order of range()
    • Python check list is empty
    • Python get ASCII value from character
    • An A-Z of useful Python tricks
    • Python nested function variable scope
    • Python reverse a list
    • Python priority queue -- heapq
  • C++ Notes
    • Templates
    • std::string (C++) and char* (or c-string "string" for C)
    • C++ printf and cout
    • Class Member Function
    • Inline
    • Scope Resolution Operator ::
    • Constructor
    • Destructor
    • Garbage Collection is Critical
    • C++ Question Lists
  • Operating System
    • Basics
    • Mutex & Semaphore
    • Ticket Selling System
    • OS and Memory
    • Sort implementation in STL
    • Compile, link, loading & run
    • How to understand Multithreading and Multiprocessing from the view of Operating System
  • Linux & Productivity
    • Jupyter Notebook on Remote Server
    • Nividia-smi monitoring
  • Leetcode Notes
    • Array
      • 11. Container With Most Water
      • 35. Search Insert Position
    • Linked List
      • Difference between Linked List and Array
      • Linked List Insert
      • Design of Linked List
      • Two Pointers
        • 141. Linked List Cycle
        • 142. Linked List Cycle II
        • 160. Intersection of two Linked List
        • 19. Remove N-th node from the end of linked list
      • 206. Reverse Linked List
      • 203. Remove Linked List Elements
      • 328. Odd Even Linked List
      • 234. Palindrome Linked List
      • 21. Merge Two Sorted Lists
      • 430. Flatten a Multilevel Doubly Linked List
      • 430. Flatten a Multilevel Doubly Linked List
      • 708. Insert into a Cyclic Sorted List
      • 138. Copy List with Random Pointer
      • 61. Rotate List
    • Binary Tree
      • 144. Binary Tree Preorder Traversal
      • 94. Binary Tree Iterative In-order Traverse
    • Binary Search Tree
      • 98. Validate Binary Search Tree
      • 285. Inorder Successor in BST
      • 173. Binary Search Tree Iterator
      • 700. Search in a Binary Search Tree
      • 450. Delete Node in a BST
      • 701. Insert into a Binary Search Tree
      • Kth Largest Element in a Stream
      • Lowest Common Ancestor of a BST
      • Contain Duplicate III
      • Balanced BST
      • Convert Sorted Array to Binary Search Tree
    • Dynamic Programming
      • 198. House Robber
      • House Robber II
      • Unique Path
      • Unique Path II
      • Best time to buy and sell
      • Partition equal subset sum
      • Target Sum
      • Burst Ballons
    • DFS
      • Clone Graph
      • General Introduction
      • Array & String
      • Sliding Window
  • Quotes
    • Concert Violinist Joke
    • 船 Ship
    • What I cannot create, I do not understand
    • Set your course by the stars
    • To-do list
Powered by GitBook
On this page
  • 20跟21有什么区别
  • 让一个函数Return两次
  • 循环几次?
  • 一石三鸟
  • 又是数字,256和257有什么区别?
  1. Python notes

Python WTF

PreviousPython Class' Instance method, Class method, and Static Methods DemystifiedNextPython find first value index in a list: [list].index(val)

Last updated 6 years ago

Python是一门清晰易学的语言,可是这不代表我们Python没有黑暗料理,下面我就挑选了几个能让你大呼"卧槽,怎么会这样"的程序,这些例子不光有趣,也能够加深我们对于Python细节的理解,看看你自己能不能解释吧。

本文取材于下面这个GitHub repository。

以下代码如果不信请手动尝试,测试环境:Python 3.6

20跟21有什么区别

In [1]: 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
Out[1]: True

In [2]: 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
Out[2]: False

第一次看到这个例子的时候我的心里面充满了wtf,20跟21有什么区别为什么结果不一样?原因是,python在进行内部优化的时候会做常量替换的操作,也就是把 'a' * 20这种语句替换成'aaaaaaaaaaaaaaaaaaaa',这样运行的时候节省时间,而刚好,小于等于20的时候会做这个优化,而大于20就不做这个优化了。。。

让一个函数Return两次

In [3]: def some_func():
   ...:     try:
   ...:         return 'from_try'
   ...:     finally:
   ...:         return 'from_finally'
   ...:     

In [4]: some_func()
Out[4]: 'from_finally'

一般的Python教程会告诉你,当函数执行到第一个return的时候会退出,剩下的语句不再执行。然而如果是这样的话上面的代码中我们的somefunc()应该返回的是'from_try',但结果却不是。这个现象的原因是finally后面的语句永远会执行,而函数的返回值由最后一个return语句决定,所以函数的返回值是finally语句中的返回值。

循环几次?

你猜下面的代码会循环几次

for i in range(4):
    print(i)
    i = 10

有些同学可能会猜只会循环一次,然后正确的输出是

0
1
2
3

循环了4次,所以i=10这个语句完全没用了吗?是的,这跟Python的for循环的机制有关,每次在循环体之前,下一个需要的值先会产生好然后赋值给循环变量,这里的i。也就是说,虽然循环体中有一个i = 10,但下次循环前for又会做一个i=2或者i=3的操作,把i=10覆盖了。

一石三鸟

row = [''] * 3
board = [row] * 3
print(board)
==> [['', '', ''], ['', '', ''], ['', '', '']]

现在我们赋个值给第一个元素,再看看结果

board[0][0] = 'X'
print(board)
==> [['X', '', ''], ['X', '', ''], ['X', '', '']]

What?为什么有三个元素都变成了X,我们明明值赋了一个值啊?这是因为[row] * 3这个操作实际上没有复制row,而只是创建了三个object reference,也就是board[0] board[1] board[2]这三个元素其实指向了同一个列表row,那么改变board[0][0]其实就是改变row[0],也同时改变了board[1][0] board[2][0]。

又是数字,256和257有什么区别?

In [45]: a = 256
In [46]: b = 256
In [47]: a is b
Out[47]: True

In [48]: a = 257
In [49]: b = 257
In [50]: a is b
Out[50]: False

In [58]: a, b = 257, 257
In [59]: a is b
Out[59]: True

嗼嗼嗼,这又是怎么回事?这又引出了Python另一个优化机制,在解释器开始的时候,会初始化-5到256这些数字,因为这些数字是常用的。所以a=256实际上是把a指向了已经创建好的256,b也同理。而257并没有预先创建好,每一行的代码在解释器里面又是单独优化的,所以写b=257的时候解释器不知道已经有了一个257,又新建了一个,因此他们俩指向不同的object。但当在一行里面同时给a b赋值为257的时候,解释器优化知道这点,就只创建了一个257,所以a is b又是True了。补充说明一下,这个现象只存在于repl交互执行当中,如果你把这些语句写在一个文件里面运行,那么编译器会一起优化,所有的结果都是True了。

satwikkansal/wtfpython​github.com
LogoGitHub - satwikkansal/wtfpython: What the f*ck Python? 😱GitHub
LogoPython有趣时刻,这些代码让你大呼"卧槽,怎么会这样"知乎专栏
图标