This blog collects the pits encountered from Python 2 to Python 3 due to different writing. Gives a written notation that Python 2 and Python 3 are compatible. 1. How to be compatible with raw_input () and input ()
Python 2:
Raw_input () # Gets the input string input
() # get the numeric input
Python 3:
Input () # Get any input, convert to string
Write a program that Python2 and Python3 are compatible to receive user input:
From six.moves Import input
Six is a library that is compatible with Python 2 and Python 3. So in order to achieve compatibility effect, often need to use six. 2. Custom Ordering of Arrays
Lambda functions are often used in Python 2 to assist in the custom ordering of arrays. For example, sort a dict by value from big to small:
result = sorted (Some_dict.items (), Lambda X, y:cmp (x[1), y[1), revert=true)
If you do this in Python 3, you can cause an error:
Typeerror:must use keyword argument for key function
So, what should you do in Python 3? You can do this:
result = sorted (Some_dict.items (), Key=lambda x:x[1], reverse=true)
This is also true for Python 2. Therefore, this example will not be used to six.
Here are 2 key points:
1. Be sure to write "key=" clearly
2. A lambda expression does not have to write a comparison of 2 elements, as in Python 2, but rather a "property" to be compared. In this case, x represents each item in D.items (), and x[1] represents the "property" of the item, that is, what to take out.
(To be continued)