Python Tricks Several

Source: Internet
Author: User

Python Tricks Several

Zhaobin-april 29, 2015
You can see some common trick in Python code, and here's a simple summary.

JSON string formatting

JSON strings are often used when developing Web applications, but a longer JSON string is less readable and not easy to see inside the structure. This is the time to use Python to print the JSON string nicely.

[email protected]:/tmp# cat json.txt {"menu":  {"Breakfast":  {"English  Muffin ":  {" Price ": 7.5}, " Bread basket ":  {" price ": 20, " desc ": " Assortment of fresh baked fruit breads and muffins "}, " Fruit  Breads ":  {" Price ": 8}}, " Drink ":  {" Hot tea ":  {" Price ": 5}, " Juice ":  {"Price": 10,  "type":  ["apple",  "watermelon",  "orange"]}}}}[email  protected]:/tmp# [email protected]:/tmp# cat json.txt | python -m  json.tool{     "Menu": {         "Breakfast":  {             "Bread basket":  {                  "desc":  " assortment of fresh baked Fruit breads and muffins ",                  "Price": 20             },             "English muffin":  {                 "Price" : 7.5            },              "Fruit breads": {                  "Price": 8             }        },          "Drink": {              "Hot tea": &NBsp {                 "Price":  5            },              "Juice": {                  "Price": 10,                  "Type": [                      "Apple",                      " Watermelon ",                      "Orange"                  ]            }        }     }}[email protected]:/tmp#
else's Magical

In some scenarios we need to determine whether we are from aforIn the LoopbreakJumped out and was only forbreakOut of the situation to do the appropriate treatment. At this time, it is common practice to use aflagVariable to identify whether it is from aforIn the loop. As shown in the following example, see if there is a multiple of 17 between 60 and 80.

flag = falsefor item in xrange (60, 80):     if item  % 17 == 0:        flag = True         breakif flag:    print  "Exists at  least one number can be divided by 17 "

In fact, this can be achieved with the else same effect without introducing new variables.

For item in xrange: If Item% = = = 0:flag = True breakelse:print "exist"
SetDefault method

dictionary   is  python is a very powerful built-in data structure, but it's still inconvenient to use, such as when nesting in multiple layers, we usually write

Dyna_routes = {}method = ' GET ' Whole_rule = none# Some other logical processing ... if method in Dyna_routes:dyna_routes[method].append (whole _rule) Else:dyna_routes[method] = [Whole_rule]

In fact, there is a simpler way of writing that can achieve the same effect

Self.dyna_routes.setdefault (method, []). Append (Whole_rule)

Or you can use the ' collections.defaultdict ' module

Import collectionsdyna_routes = collections.defaultdict (list) ... dyna_routes[method].append (whole_rule)

The writer is ONEAPM engineer Zhaobin, want to read more good technical articles, please visit the ONEAPM Official technology blog.



Python Tricks Several

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.