标签:
1.列表
list[起始:结尾:增量]
值传递与地址传递
a = [2,1] b = a #地址传递 b = a[:] 值传递 a.sort() print a #[1,2] print b #[1,2]
2.排序sort()
d = {1:‘s‘,2:‘a‘} print sorted(d.items(), key = lambda x:x[1])/*按list元素的第2个元素排序*/
#sorted(iterable, cmp=None/*函数*/, key=None/*函数*/, reverse=False) ll = [‘aaa‘,‘a‘,‘aa‘] ll.sort( key = len )#key值是总要调用的函数 print ll
print sorted("Sorting1234", key=lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x))#[‘g‘, ‘i‘, ‘n‘, ‘o‘, ‘r‘, ‘t‘, ‘S‘, ‘1‘, ‘3‘, ‘2‘, ‘4‘]
3.匿名函数lambda
#lambda 形参:返回值 lambda x:x+1
4....for ... in ... if ...
a = [1,2,3] print [i**2 for i in a if i>0]
5.filter map reduce
filter(function, sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/String/Tuple(取决于sequence的类型)返回
print filter( lambda x:x!=‘a‘, ‘abcd‘ ) #‘bcd‘
map(function, sequence) :对sequence中的item依次执行function(item),见执行结果组成一个List返回:
print map( lambda x:x+1, range(3) ) #[1,2,3]
reduce(function, sequence, starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对List求和
print reduce( lambda x,y:x+y, range(3), 10 ) #13
6.生成器 generator
a = (x * x for x in range(3)) for i in a:print i
7. range(起始,结尾,增量)
print range(1,9,2) #[1, 3, 5, 7]
8. ...?...:...
(1) variable = a if expression else b #完全等价 (2) variable = (expression and [b] or [c])[0] (3) variable = expression and b or c #不完全等价,b 不能为False
f
标签:
原文地址:http://www.cnblogs.com/woxinfeixiang2015/p/5494949.html