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 afor
In the Loopbreak
Jumped out and was only forbreak
Out of the situation to do the appropriate treatment. At this time, it is common practice to use aflag
Variable to identify whether it is from afor
In 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