1.判断对象是否为空(长度为0,值为None或0 )
2.a是否为b子串
3.打印美化,使用string对象的join方法,string.join(list,sep)
a = ['a','b','c']
import string
print string.join(a,',')
#更常用形式
print ','.join(a)
4.Lambda表达式
lambda variable(s) : expression
#eg1:
sum = lambda x,y :x+y
#调用方法
sum(1,6)
#eg2:
a = [1,2,3,4]
map(lambda x:x*x,a)
5.List 相关
map
numbers = [1,2,3,4,5]
squares = map(lambda x: x*x, numbers)
filter
numbers_under_4 = filter(lambda x: x < 4, numbers)
map and filter at once
#计算不大于4的数的平方
squares_numbers_under_4 = map(lambda x: x*x, filter(lambda x: x < 4, numbers))
comprehensions
用列表推导重写上面三个例子
squares = [x*x for in numbers]
numbers_under_4 = [x for x in numbers if x < 4]
squares_numbers_under_4 = [x*x for x in numbers if x < 4]
comprehensions 的for 嵌套
[(x, y, x * y) for x in (0,1,2,3) for y in (0,1,2,3) if x < y]
等价于
for x in (0,1,2,3):
for y in (0,1,2,3):
if x < y:
print (x, y, x*y),
generator
generator与comprehensions区别在于:
1.采用(),而非[] ;
eg: s = (x*x for x in numbers if x < 4)
2.comprehensions一次加载整个结果列表到内存中,generator结果则采用生成器特有
的迭代访问接口next(),用于循环操作时,效率较高。
Ps: range 和 xrange()存在类似的区别。
reduce
1-100的和
sum = reduce(lambda x,y:x+y, xrange(1,101))
enumrate 返回索引和值的迭代器
strings = ['a', 'b', 'c', 'd', 'e']
#孰优孰劣,一目了然
for index in xrange(len(strings)):
print index,strings[index]
for x,y in enumerate(strings):
print x,y
any & all
numbers = [1,10,100,1000,10000]
是否存在小于10的元素
any(number < 10 for x in numbers)
是否所有元素都小于10
all(number < 10 for x in numbers)
zip 拉链
letters = ['a', 'b', 'c']
numbers = [1, 2, 3]
zipped_list = zip(letters, numbers)
[('a',1),('b',2),('c',3)]
set(some_list) 从列表构建一个set,自动去除重复元素
max min sum 列表上的内建操作,记得不要被自己定义的变量名覆盖就好
6.Dict相关
用关键字参数构建字典
items() 字典转换到列表,结果是tuple列表
keys() 得到字典的关键字列表
values() 得到值列表
iterkeys itervalues iteritems 得到的是相应的迭代器
形如[(a,b),..] [[a,b],..]的列表可以转换成字典{a:b,...},并能作为dict类型的关键字参数
dict_as_list = [['a', 1], ['b', 2], ['c', 3]]
dictionary = dict(dict_as_list, d=4, e=5)
字典推导
emails = {'Dick': 'bob@example.com', 'Jane': 'jane@example.com', 'Stou': 'stou@example.net'}
email_at_dotcom = dict( [name, '.com' in email] for name, email in emails.iteritems() )
email_at_dotcom = dict([ [name, '.com' in email] for name, email in emails.iteritems()] )
email_at_dotcom = dict([ [name, '.com' in email] for name, email in emails.items()] )
#思考:以上三种写法的效率??
(待续)
cite:Python Tips, Tricks, and Hacks