Swap variables
x = 6y = 5x, y = y, xprint x>>> 5print y>>> 6
If statement in row
print "Hello" if True else "World">>> Hello
Connection
The last way to do this is to be 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 worldprint `1` + " world">>> 1 worldprint 1, "world">>> 1 worldprint nfc, 1>>> [‘Packers‘, ‘49ers‘] 1
Calculation techniques
#向下取整print 5.0//2>>> 2# 2的5次方print 2**5>> 32
Note the division of floating-point numbers
print .3/.1>>> 2.9999999999999996print .3//.1>>> 2.0
Numerical comparison
x = 2if 3 > x > 1: print x>>> 2if 1 < x > 0: print x>>> 2
Two simultaneous iteration of lists
nfc = ["Packers", "49ers"]afc = ["Ravens", "Patriots"]for teama, teamb in zip(nfc, afc): print teama + " vs. " + teamb>>> Packers vs. Ravens>>> 49ers vs. Patriots
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
List derivation
A list of known, brush to select even list method:
numbers = [1,2,3,4,5,6]even = []for number in numbers: if number%2 == 0: even.append(number)
Replace it with the following
numbers = [1,2,3,4,5,6]even = [number for number in numbers if number%2 == 0]
Dictionary derivation
teams = ["Packers", "49ers", "Ravens", "Patriots"]print {key: value for value, key in enumerate(teams)}>>> {‘49ers‘: 1, ‘Ravens‘: 2, ‘Patriots‘: 3, ‘Packers‘: 0}
Initialize the value of the list
items = [0]*3print items>>> [0,0,0]
Convert a list to a string
teams = ["Packers", "49ers", "Ravens", "Patriots"]print ", ".join(teams)>>> ‘Packers, 49ers, Ravens, Patriots‘
Get elements from a dictionary
Do not use the following methods
data = {‘user‘: 1, ‘name‘: ‘Max‘, ‘three‘: 4}try: is_admin = data[‘admin‘]except KeyError: is_admin = False
Replaced by
data = {‘user‘: 1, ‘name‘: ‘Max‘, ‘three‘: 4}is_admin = data.get(‘admin‘, False)
Get child list
x = [1,2,3,4,5,6]#前3个print x[:3]>>> [1,2,3]#中间4个print x[1:5]>>> [2,3,4,5]#最后3个print x[-3:]>>> [4,5,6]#奇数项print x[::2]>>> [1,3,5]
Source: 17 Tips for beginners in Python
17 Tips for Beginners in Python