标签:
1.lambda lambda其实就是一条语句,lambda(x):body。x是lambda函数的参数,参数可以有任意多个(包括可选参数);body是函数体,只能是一个表达式,并且直接返回该表达式的值。
>>>f=lambda x:x+1
>>>f(2)
3
>>>(lambda x,y:x+y)(2,3)
5
2.filter filter(func, list)接受两个参数:一个函数func和一个列表list,返回一个列表。函数func只能有一个参数。filter的功能:列表中所有元素作为参数传递给函数,返回可以另func返回真的元素的列表
>>>l=[‘abc‘,‘acd‘,‘1245‘,‘ddad‘,‘aaa‘]
>>> def func(s):
return s.startswith(‘a‘)
>>>filter(func, l)
[‘abc‘,‘acd‘,‘aaa‘]
>>> li = [1,2,3,4]
>>> filter(lambda x: x>2, li)
[3, 4]
2.1 循环过程中根据条件返回
>>> {x for x in ‘abracadabra‘ if x not in ‘abc‘}
set([‘r‘, ‘d‘])
3.zip zip函数接受任意多个序列作为参数,将所有序列按相同的索引组合成一个元素是各个序列合并成的tuple的新序列,新的序列的长度以参数中最短的序列为准。另外(*)操作符与zip函数配合可以实现与zip相反的功能,即将合并的序列拆成多个tuple
>>>x=[1,2,3]
>>>y=[‘a‘,‘b‘,‘c‘]
>>>zip(x,y)
[(1,‘a‘),(2,‘b‘),(3,‘c‘)]
>>>zip(*zip(x,y))
[(1,2,3),(‘a‘,‘b‘,‘c‘)]
4.map为操作list,返回list,绑定的函数为修改list中每一个值的函数
>>> list=[1,2,3]
>>> map(lambda x : x*2,list)
>>> [2, 4, 6]
5.reduce为逐次操作list里的每项,接收的参数为 2个,最后返回的为一个结果
>>> def func(x,y):
>>> return x+y
>>> reduce(func,(1,2,3))
>>> 6
6.sorted字典排序
>>> import operator
>>> x = {1:2, 3:4, 4:3, 2:1, 0:0}
>>> sorted(x.iteritems(), key=operator.itemgetter(1), reverse=True)
[(3, 4), (4, 3), (1, 2), (2, 1), (0, 0)]
>>> sorted(x.iteritems(), key=lambda x : x[1], reverse=False)
[(0, 0), (2, 1), (1, 2), (4, 3), (3, 4)]
7.列表字典排序
>>> li = [{‘name‘:‘wang‘, ‘age‘:30}, {‘name‘:‘zhang‘, ‘age‘:20}, {‘name‘:‘li‘, ‘age‘:25}]
>>> sorted(li, key=lambda x : x[‘name‘], reverse=False)
[{‘age‘: 25, ‘name‘: ‘li‘}, {‘age‘: 30, ‘name‘: ‘wang‘}, {‘age‘: 20, ‘name‘: ‘zhang‘}]
>>> sorted(li, key=operator.itemgetter(‘name‘), reverse=True)
[{‘age‘: 20, ‘name‘: ‘zhang‘}, {‘age‘: 30, ‘name‘: ‘wang‘}, {‘age‘: 25, ‘name‘: ‘li‘}]
8.翻转字符串
>>> s = "abcd"
>>> s[::-1]
‘dcba‘
>>> "".join(sorted(list(s),reverse=True))
‘dcba‘
9.元祖(tuple)、字典(dict)之间转换
>>> t = ((1,"a"),(2,"b"))
>>> dict(t) #元祖转字典
{1: ‘a‘, 2: ‘b‘}
>>> d = dict(t)
>>> d.items() #字典转元祖
[(1, ‘a‘), (2, ‘b‘)]
>>> t = (1,"a")
>>> dict([t]) #单个元祖转字典
{1: ‘a‘}
>>> d = dict([t])
>>> d.popitem()
(1, ‘a‘)
>>> d.items()[0] #单个字典转元祖
(1, ‘a‘)
增加键值名称
>>> li = [{1:"a"},{2:"b"}]
>>> [dict(zip(("key","value"), obj.items()[0])) for obj in li]
[{‘value‘: ‘a‘, ‘key‘: 1}, {‘value‘: ‘b‘, ‘key‘: 2}]
>>> map(lambda x: dict(zip(("key","value"), x.items()[0])),li)
[{‘value‘: ‘a‘, ‘key‘: 1}, {‘value‘: ‘b‘, ‘key‘: 2}]
>>> li2 = [{‘value‘: ‘a‘, ‘key‘: 1}, {‘value‘: ‘b‘, ‘key‘: 2}]
>>> [{obj["key"]:obj["value"]} for obj in li2]
[{1: ‘a‘}, {2: ‘b‘}]
列表内对象值分组
>>> li = [{"k":"1", "v":"v1"},{"k":"2", "v":"v2"},{"k":"1", "v":"v3"}]
>>> keys = set(map(lambda x:x["k"], li)) # 取出key值
>>> newlist = [{"k":x, "v":[y["v"] for y in li if y["k"]==x]} for x in keys]
>>> print newlist
[{‘k‘: ‘1‘, ‘v‘: [‘v1‘, ‘v3‘]}, {‘k‘: ‘2‘, ‘v‘: [‘v2‘]}]
10. 打印一个对象的所有属性和值
for property, value in vars(theObject).iteritems():
print property, ": ", value
这个做法其实就是 theObject.__dict__ , 也就是 vars(obj) 其实就是返回了 o.__dict__
11.列表分页
>>> mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print [mylist[i:i+4] for i in range(0, len(mylist), 4)]
[[1, 2, 3, 4], [5, 6, 7, 8], [9]]
12.列表步长
语法:L[start:stop:step]
mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
print i,
# prints 1 3 5 7 9
for i in mylist[1::2]:
print i,
# prints 2 4 6 8 10
>>> range(1, 10, 2)
[1, 3, 5, 7, 9]
12. python字符串格式化,2.7之后增加新的字符串格式化方法format, 之前都是用%符号
>>> ‘{},{}‘.format(‘aa‘,‘bb‘)
‘aa,bb‘
>>> "{0},{2},{1}".format(1,2,3)
‘1,3,2‘
>>> "{0},{2},{1},{str}".format(1,2,3,str="string")
‘1,3,2,string‘
>>> ‘{0[0]},{0[1]}‘.format([‘aa‘,"bb"])
‘aa,bb‘
>>> ‘{:>10}‘.format(‘12‘) # 字符串左边空格填充
‘ 12‘
>>> ‘{:a<10}‘.format(‘12‘) # 字符串右边字母"a"填充
‘12aaaaaaaa‘
>>> ‘{:.2f}‘.format(321.33345) # 浮点类型
‘321.33‘
>>> ‘{:b}‘.format(17) # 格式化为二进制
‘10001‘
>>> ‘{:x}‘.format(17) # 十六进制
‘11‘
>>> " " * 4 # 复制多个字符串
‘ ‘
13. 随机数
随机选取字符串:
>>> import random
>>> random.choice ( [‘apple‘, ‘pear‘, ‘peach‘, ‘orange‘, ‘lemon‘] )
‘lemon‘
洗牌:
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]
多个字符中选取特定数量的字符:
>>> random.sample(‘abcdefghij‘,3)
[‘a‘, ‘d‘, ‘b‘]
随机整数:
>>> random.randint(0,99)
21
随机选取0到100间的偶数:
>>> random.randrange(0, 101, 2)
42
14.动态对象操作
14.1 动态执行表达式
>>> x = 1
>>> print eval(‘x+1‘) # 该函数将字符串str当成有效Python表达式来求值,并返回计算结果,但不能动态更新值,如:eval("x=2")会报错。
2
14.2 动态获取更新变量值
>>> d = {"name":"wei"}
>>> d2 = {"age":20}
>>> vars()[‘d‘]
{‘name‘: ‘wei‘}
>>> vars()[‘d‘].update(d2) # 如果全局变量使用globals()
>>> print d
{‘age‘: 20, ‘name‘: ‘wei‘}
>>> d3 = {"phone":"139"}
>>> exec("d.update(d3)")
>>> print d
{‘phone‘: ‘139‘, ‘age‘: 20, ‘name‘: ‘wei‘}
>>> print vars()["d"]
{‘phone‘: ‘139‘, ‘age‘: 20, ‘name‘: ‘wei‘}
>>> print exec("d") # exec语句将字符串str当成有效Python代码来执行,但不返回值。
File "<input>", line 1
print exec("d")
^
SyntaxError: invalid syntax
14.3 动态获取设置属性值
u = User.objects.get(id=1)
name = getattr(u, "username", "wei") # 第三个参数未默认值
kwargs = {"username": name}
User.objects.filter(id=1).update(**kwargs)
setattr(u, "username", "wei")
标签:
原文地址:http://www.cnblogs.com/weiok/p/4653378.html