1.
cities = ['Marseille', 'Amsterdam', 'New York', 'Londom'] # the good way for i, city in enumerate(cities): print(i, city)
2.
x_list = [1, 2, 3] y_list = [2, 4, 6] # the good way for x, y in zip(x_list, y_list): print (x, y)
3.
x = 10 y = -10 # the good way x, y = y, x print ('After: x = %d, y = %d' % (x, y))
4.
ages = { 'Mary' : 31, 'Honathan' : 28 } # the good way age = ages.get('Dick', 'Unknow') print ('Dick is %s years old' % age)
5.
needle = 'd' haystack = ['a', 'b', 'c', 'd'] # the good way for letter in haystack: if needle == letter: print ('Found!') break else: print ('Not found!')
6.
# the good way with open('pimpin-aint-easy.txt') as f: for line in f: print (line)
7.
print ('Converting!') try: print (int('1')) except: print ('Conversion failed!') else: print ('Conversion uccessful!') finally: print ('Done!')
8.
普通的方法,第一个参数需要是self,它表示一个具体的实例本身。 如果用了staticmethod,那么就可以无视这个self,而将这个方法当成一个普通的函数使用。 而对于classmethod,它的第一个参数不是self,是cls,它表示这个类本身。 >>> class A(object): def foo1(self): print "Hello",self @staticmethod def foo2(): print "hello" @classmethod def foo3(cls): print "hello",cls
9. Goal: Check if my version is the latest
lastest_python = 3 my_python = 2 msg = 'Update available' if lastest_python > my_python else 'Up to daye' print('Update check: {}'.format(msg)) latest_python = [3, 5, 2] my_python = [3, 5, 1] msg = 'Update available' if latest_python > my_python else 'Up to date' print('Update check: {}'.format(msg)
10. python之字符串格式化(format)
用法:
它通过{}和:来代替传统%方式
1、使用位置参数
要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表
>>> li = ['hoho',18] >>> 'my name is {} ,age {}'.format('hoho',18) 'my name is hoho ,age 18' >>> 'my name is {1} ,age {0}'.format(10,'hoho') 'my name is hoho ,age 10' >>> 'my name is {1} ,age {0} {1}'.format(10,'hoho') 'my name is hoho ,age 10 hoho' >>> 'my name is {} ,age {}'.format(*li) 'my name is hoho ,age 18'
2、使用关键字参数
要点:关键字参数值要对得上,可用字典当关键字参数传入值,字典前加**即可
>>> hash = {'name':'hoho','age':18} >>> 'my name is {name},age is {age}'.format(name='hoho',age=19) 'my name is hoho,age is 19' >>> 'my name is {name},age is {age}'.format(**hash) 'my name is hoho,age is 18'
3、填充与格式化
:[填充字符][对齐方式 <^>][宽度]
>>> '{0:*>10}'.format(10) ##右对齐 '********10' >>> '{0:*<10}'.format(10) ##左对齐 '10********' >>> '{0:*^10}'.format(10) ##居中对齐 '****10****'
4、精度与进制
>>> '{0:.2f}'.format(1/3) '0.33' >>> '{0:b}'.format(10) #二进制 '1010' >>> '{0:o}'.format(10) #八进制 '12' >>> '{0:x}'.format(10) #16进制 'a' >>> '{:,}'.format(12369132698) #千分位格式化 '12,369,132,698'
5、使用索引
>>> li ['hoho', 18] >>> 'name is {0[0]} age is {0[1]}'.format(li) 'name is hoho age is 18
11. Goal: Check if my version is the latest
# Ordered by population cities = ['Groningen', 'Marseille', 'Paries', 'Buenos Aires', 'Mumbai'] smallest, *rest, largest = cities print('smallest: {}'.format(smallest)) print('largest: {}'.format(largest))
12. 未知数量参数
def draw_curve(*curves): fig, axes = plt.subplots(nrows=1, figsize=(10, 8)) for curve_i, curve_name in enumerate(curves): 。。。