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": {"Chinese Muffin": {"price": 7.5}, "Bread basket": {"PRI"} Ce ":", "desc": "Assortment of fresh baked fruit breads and muffins"}, "fruit breads": {"Price": 8}}, "Drink": {"Hot Tea" : {"Price": 5}, "Juice": {"Price": Ten, "type": ["apple", "watermelon", "orange"]}}}}[email protected]:/tmp# [email& nbsp;protected]:/tmp# Cat Json.txt | Python-m json.tool{"Menu": {"breakfast": {"Bread basket": {"desc": "Assortment of Fresh baked fruit breads and muffins "," price ": +}," 中文版 Muffin ": { ' Price ': 7.5}, "Fruit breads": {"Price": 8}}, "Drin K ": {" Hot Tea ": {' 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 for
jumping out of a loop break
and dealing with it only for the case of a break
bounce. It is often our practice to use a flag
variable to identify whether it for
jumps out of 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(60, 80): if item % 17 == 0: flag = True breakelse: print "exist"
SetDefault method
dictionary
Is python
a very powerful built-in data structure, but it is still inconvenient to use, such as in multi-layered nesting when we usually write this
dyna_routes = {}method = ‘GET‘whole_rule = None# 一些其他的逻辑处理...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