current position：Home>Do you know the fuzzy semantics in Python syntax?
Do you know the fuzzy semantics in Python syntax?
2022-01-30 00:09:25 【Python learner】
1. The slice does not perform cross-border inspection and error reporting
What will be the output of the following code ？
list = ['a', 'b', 'c', 'd', 'e'] print list[10:] Copy code
The following code will output an empty list  , Will not produce IndexError error . As expected , Try using more than the number of members index To get members of a list .
for example , Try to get list And later members , It can lead to IndexError .
However , Try to get the slice of the list , At the beginning index Exceeding the number of members will not produce IndexError, It just returns an empty list .
This has become a particularly disgusting problem , Because there are no errors when running , Lead to bug It's hard to track .
2. Creation of empty list
1ist = [[ ]] * 5 list # output? list.append(10) list # output? list.append(20) list # output? list.append (30) list # output? Copy code
2,4,6,8 What results will be output on the line ？ Try to explain .
The output is as follows
[,,,,] [,,,,] [[10,20],[10,20],[10,20]] [[10,20],[10,20],[10,20],[10,20],[10,20],30] Copy code
The output of the first line is intuitively easy to understand , for example list = [ [ ] ] * 5 Is simply created 5 An empty list . However , Understanding expressions list=[ [ ] ] * 5 The key point is that it doesn't create a list of five separate lists , Instead, it is a list created with five references to the same list . Only to understand this point , We can better understand the next output . 3. The key is coming. ： Delay binding of closures
What will be the output of the following code ？ Please explain .
#Python Learning exchange group ：531509025 def multipliers(): return [lambda x : i*x for i in range(4)] print [m(2) for m in multipliers()] Copy code
How do you modify the above multipliers The definition of produces the desired results ？ The output of the above code is [6, 6, 6, 6] , Not what we think [0, 2, 4, 6] .
The reason for the above problems is Python Delay binding of closures . This means that when an internal function is called , The value of the parameter is searched in the closure . therefore , When any multipliers() When the returned function is called ,i The value of will be found in the nearby range . At that time , Whether the returned function is called or not ,for The cycle is complete ,i Given the final value 3.
therefore , Each time the function returned is multiplied by the value passed 3, Because the value of the previous code is 2, They all end up returning 6(3*2). It happened that ,《The Hitchhiker’s Guide to Python》 Also pointed out , With the lambdas There is also a widely misunderstood point of knowledge about functional correlation , But with this case Dissimilarity . from lambda There is nothing special about the functions created by expressions , It's actually with def The function created is the same .
Here are some ways to solve this problem .
One solution is to use Python generator .
def multipliers(): for i in range(4): yield lambda x : i * x Copy code
Another solution is to create a closure , Use the default function to bind immediately .
def multipliers(): return [lambda x, i=i : i * x for i in range(4)] Copy code
Another alternative is , Use partial functions ：
from functools import partial from operator import mul def multipliers(): return [partial(mul, i) for i in range(4)] Copy code
author[Python learner],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Install tensorflow and python 3.6 in Windows 7
- Python collects and monitors system data -- psutil
- Getting started with Python - object oriented - special methods
- Teach you how to use Python to transform an alien invasion game
- You can easily get started with Excel. Python data analysis package pandas (VI): sorting
- Implementation of top-level design pattern in Python
- Using linear systems in python with scipy.linalg
- How to get started quickly? How to learn Python
- Modifying Python environment with Mac OS security
- Better use atom to support jupyter based Python development
guess what you like
Better use atom to support jupyter based Python development
Fast power modulus Python implementation of large numbers
Python architects recommend the book "Python programmer's Guide" which must be read by self-study Python architects. You are welcome to take it away
Decoding the verification code of Taobao slider with Python + selenium, the road of information security
Python game development, pyGame module, python implementation of skiing games
Python collects and monitors system data -- psutil
Python + selenium automated test: page object mode
You can easily get started with Excel. Python data analysis package pandas (IV): any grouping score bar
Opencv skills | saving pictures in common formats as transparent background pictures (with Python source code) - teach you to easily make logo
Python ThreadPoolExecutor restrictions_ work_ Queue size
- Python generates and deploys verification codes with one click (Django)
- With "Python" advanced, you can catch all the advanced syntax! Advanced function + file operation, do not look at regret Series ~
- At the beginning of "Python", you must see the series. 10000 words are only for you. It is recommended to like the collection ~
- [Python kaggle] pandas basic exercises in machine learning series (6)
- Using linear systems in python with scipy.linalg
- The founder of pandas teaches you how to use Python for data analysis (mind mapping)
- Using Python to realize national second-hand housing data capture + map display
- Python image processing, automatic generation of GIF dynamic pictures
- Pandas advanced tutorial: time processing
- How to make Python run faster? Six tips!
- Django: use of elastic search search system
- Python 3.10 official release
- Python chat room (Tkinter writing interface, streaming, socket to realize private chat, group chat, check chat records, Mysql to store data)
- This pandas exercise must be successfully won
- [algorithm learning] sword finger offer 64 Find 1 + 2 +... + n (Java / C / C + + / Python / go / trust)
- leetcode 58. Length of Last Word（python）
- Problems encountered in writing the HTML content of articles into the database during the development of Django blog
- Understand Python's built-in function and add a print function yourself
- Python implements JS encryption algorithm in thousands of music websites
- leetcode 35. Search Insert Position（python）
- leetcode 1829. Maximum XOR for Each Query（python）
- [introduction to Python visualization]: 12 small examples of complete data visualization, taking you to play with visualization ~
- Learning this Python library can reduce at least 100 lines of code
- leetcode 67. Add Binary（python）
- Regular re parameter replacement of Python 3 interface automation test framework
- V. pandas based on Python
- Only 15 lines of code is needed for face detection! (using Python and openCV)
- [Python crawler Sao operation] you can crawl Sirius cinema movies without paying
- leetcode 69. Sqrt(x)（python）
- Teach you to read the source code of Cpython (I)
- Snowball learning started in the fourth quarter of Python. One needs three meals. I have a new understanding of Python functional programming, process-oriented, object-oriented and functional
- leetcode 88. Merge Sorted Array（python）
- Don't you know more about a python library before the end of 2021?
- Python crawler web page parsing artifact XPath quick start teaching!!!
- Use Python and OpenCV to watermark the image
- String and related methods of Python data type introduction
- Heapq module of Python module
- Introduction to beautiful soup of Python crawler weapon, detailed explanation, actual combat summary!!!
- Event loop of Python collaboration series
- Django docking pin login system