A few pits from Python 2 to Python 3 __python

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.