Life is short, learn Python! When you first know Python language, you feel that Python meets all the requirements for programming language when you go to school. The efficient programming skills of Python language make those who have been forced to learn c or c + + for four years excited and finally relieved. High level language, if you can't do this, what's high level?
01 exchange variables
>>>a=3 >>>b=6
In this case, if you want to exchange variables, you must need an empty variable in c + +. But python doesn't need it, just one line. You can see it clearly
>>>a,b=b,a >>>print(a)>>>6 >>>ptint(b)>>>5
02 dictionary derivations and set derivations
Most Python programmers know and use list derivations. If you are not familiar with the concept of list completions - a list completions is a shorter and more concise way to create a list.
>>> some_list = [1, 2, 3, 4, 5] >>> another_list = [ x + 1 for x in some_list ] >>> another_list [2, 3, 4, 5, 6]
Since python 3.1, we can use the same syntax to create sets and dictionary tables:
>>> # Set Comprehensions >>> some_list = [1, 2, 3, 4, 5, 2, 5, 1, 4, 8] >>> even_set = { x for x in some_list if x % 2 == 0 } >>> even_set set([8, 2, 4]) >>> # Dict Comprehensions >>> d = { x: x % 2 == 0 for x in range(1, 11) } >>> d {1: False, 2: True, 3: False, 4: True, 5: False, 6: True, 7: False, 8: True, 9: False, 10: True}
In the first example, we use some_ Based on list, a set with non repeating elements is created, and the set contains only even numbers. In the example of dictionary table, we created a non repeated integer between 1 and 10, and value is Boolean to indicate whether the key is even. Another thing worth noting here is the literal representation of sets. We can simply create a collection in this way:
>>> my_set = {1, 2, 1, 2, 3, 4} >>> my_set set([1, 2, 3, 4])
Instead of using the built-in function set().
03 Counter object is used for counting
This sounds obvious, but it is often forgotten. Counting a thing is a common task for most programmers, and it's not very challenging in most cases - there are several ways to do this task more easily. There is a subclass of the built-in dict class in Python's collections class library, which is specially used for this kind of thing:
>>> from collections import Counter >>> c = Counter( hello world ) >>> c Counter({ l : 3, o : 2, : 1, e : 1, d : 1, h : 1, r : 1, w : 1}) >>> c.most_common(2) [( l , 3), ( o , 2)]
04 beautiful print JSON
JSON is a very good form of data serialization, which is widely used by various API s and web service s today. Using python's built-in JSON processing can make the JSON string readable to a certain extent, but when encountering large data, it appears as a long and continuous line, which is difficult for human eyes to watch. In order to make JSON data more friendly, we can use indent parameter to output beautiful JSON. This is especially useful when programming interactively or logging on the console:
>>> import json >>> print(json.dumps(data)) # No indention {"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "name": "Joe", "lactose_intolerant": false}]} >>> print(json.dumps(data, indent=2)) # With indention { "status": "OK", "count": 2, "results": [ { "age": 27, "name": "Oz", "lactose_intolerant": true }, { "age": 29, "name": "Joe", "lactose_intolerant": false } ] }
Similarly, using the built-in pprint module can also make the printout of anything else more beautiful.
05 solve FizzBuzz
Some time ago Jeff Atwood promoted a simple programming exercise called FizzBuzz. The question is quoted as follows:
Write a program, print the number from 1 to 100, print "Fizz" in multiples of 3 to replace this number, print "Buzz" in multiples of 5, and print "FizzBuzz" in multiples of both 3 and 5.
Here is a short and interesting way to solve this problem:
for x in range(1,101): print"fizz"[x%3*len( fizz )::]+"buzz"[x%5*len( buzz )::] or x
06 if statement in line
print "Hello" if True else "World" >>> Hello
07 connection
The last method below is cool when binding two different types of objects.
nfc = ["Packers", "49ers"] afc = ["Ravens", "Patriots"] print nfc + afc >>> [ Packers , 49ers , Ravens , Patriots ] print str(1) + " world" >>> 1 world print `1` + " world" >>> 1 world print 1, "world" >>> 1 world print nfc, 1 >>> [ Packers , 49ers ] 1
08 numerical comparison
This is a simple method that I have never seen so great in many languages
x = 2 if 3 > x > 1: print x >>> 2 if 1 < x > 0: print x >>> 2
09 iterating over two lists at the same time
nfc = ["Packers", "49ers"] afc = ["Ravens", "Patriots"] for teama, teamb in zip(nfc, afc): print teama + " vs. " + teamb >>> Packers vs. Ravens >>> 49ers vs. Patriots
10 list iteration with index
teams = ["Packers", "49ers", "Ravens", "Patriots"] for index, team in enumerate(teams): print index, team >>> 0 Packers >>> 1 49ers >>> 2 Ravens >>> 3 Patriots
11 list derivation
Given a list, we can brush out the even list method:
numbers = [1,2,3,4,5,6] even = [] for number in numbers: if number%2 == 0: even.append(number)
Change to the following:
numbers = [1,2,3,4,5,6] even = [number for number in numbers if number%2 == 0]
12 dictionary derivation
Similar to list derivation, dictionaries can do the same work:
teams = ["Packers", "49ers", "Ravens", "Patriots"] print {key: value for value, key in enumerate(teams)} >>> { 49ers : 1, Ravens : 2, Patriots : 3, Packers : 0}
13 value of initialization list
items = [0]*3 print items >>> [0,0,0]
14 convert list to string
teams = ["Packers", "49ers", "Ravens", "Patriots"] print ", ".join(teams) >>> Packers, 49ers, Ravens, Patriots
15 get elements from dictionary
I admit that the try/except code is not elegant, but here is a simple way to try to find the key in the dictionary. If the corresponding value is not found, the second parameter will be set as its variable value.
data = { user : 1, name : Max , three : 4} try: is_admin = data[ admin ] except KeyError: is_admin = False
Replace with this
data = { user : 1, name : Max , three : 4} is_admin = data.get( admin , False)
16 get a subset of the list
Sometimes you only need some elements in the list. Here are some ways to get a subset of the list.
x = [1,2,3,4,5,6] #First 3 print x[:3] >>> [1,2,3] #Middle 4 print x[1:5] >>> [2,3,4,5] #Last 3 print x[3:] >>> [4,5,6] #Odd term print x[::2] >>> [1,3,5] #Even term print x[1::2] >>> [2,4,6]
In addition to the built-in data types in python, the collection module also includes some special use cases. In some cases, Counter is very practical. If you've attended Facebook hacker Cup this year, you can even find its usefulness.
from collections import Counter print Counter("hello") >>> Counter({ l : 2, h : 1, e : 1, o : 1})
17 iteration tools
Like the collections library, there is also a library called itertools, which can effectively solve some problems. One use case is to find all combinations. It can tell you all the combinations of elements in a group
from itertools import combinations teams = ["Packers", "49ers", "Ravens", "Patriots"] for game in combinations(teams, 2): print game >>> ( Packers , 49ers ) >>> ( Packers , Ravens ) >>> ( Packers , Patriots ) >>> ( 49ers , Ravens ) >>> ( 49ers , Patriots ) >>> ( Ravens , Patriots )
18 False == True
Compared with practical technology, this is a very interesting thing. In python, True and False are global variables, so:
False = True if False: print "Hello" else: print "World" >>> Hello