>>> x = 6
>>> y = 5
>>> x,y = y,x >>> print x 5 >>> print y
6
if 语句在行内 >>> print "hello" if True else "world" hello 连接 下面的最后一种方式在绑定两个不同类型的对象时显得很cool >>> zrq = ['packers','56ers'] >>> zxy = ['ravens','patriots'] >>> print zrq + zxy ['packers', '56ers', 'ravens', 'patriots'] >>> print str(2) + "world" 2world >>> print '3' + ' world' 3 world >>> print zrq,1 ['packers', '56ers'] 1 数据技巧
#除后向下取整
print 5.0//2
>>> 2
# 2的5次方
print 2**5
>> 32
注意浮点数的除法
print .3/.1
>>> 2.9999999999999996
print .3//.1
>>> 2.0
数值比较
这是我见过的诸多语言中很少有的如此棒的简单法
>>> x = 2 >>> if 3 > x >1: ... print x ... 2 >>> if 1 < x > 0: ... print x ... 2
同时迭代两个列表
>>> zrq = ['packers','123per']
>>> zxy = ['ravens','patriots']
>>> for teama,teamb in zip(zrq,zxy):
... print teama + "vs." +teamb
... packersvs.ravens
123pervs.patriot
带索引的列表迭代
>>> teams = ['zrq','zxy','hello','world']
>>> for index,team in enumerate(teams):
... print index,team ... 0 zrq
1 zxy
2 hello
3 world
列表推导式
已知一个列表,我们可以筛选出偶数列表方法:
>>> numbers = [1,2,3,4,5,6,7,8,9,10]
>>> even = []
>>> for number in numbers:
... if number % 2 ==0:
... even.append(number)
>>> even [2, 4, 6, 8, 10] 转变成如下
numbers = [1,2,3,4,5,6]
even = [number for number in numbers if number%2 == 0]
字典推导 >>> teams ['zrq', 'zxy', 'hello', 'world'] >>> print {key:value for key,value in enumerate(teams)} {0: 'zrq', 1: 'zxy', 2: 'hello', 3: 'world'} 初始化列表的值 items = [0]*3 print items >>> [0,0,0] 列表转换为字符串 {0: 'zrq', 1: 'zxy', 2: 'hello', 3: 'world'} >>> print ",".join(teams) zrq,zxy,hello,world 从字典中获取元素 我承认try/except代码并不雅致,不过这里有一种简单方法,尝试在字典中查找key,如果没有找到对应的alue将用第二个参数设为其变量值。 >>> data {0: 'zrq', 1: 'zxy', 2: 'hello', 3: 'world'} >>> try: ... is_admin = data['admin'] ... except KeyError: ... is_admin = False ...替换成这样: >>> data {0: 'zrq', 1: 'zxy', 2: 'hello', 3: 'world'} >>> is_admin = data.get('admin',False) 迭代工具 和collection 库一样,还有一个库叫itertools,对某些问题真能高效的解决,其中一个用例是查找所有组合,他能告诉你在一个组中元素的所有的组合方式 >>> teams ['zrq', 'zxy', 'hello', 'world'] >>> for game in combinations(teams,2): ... print game ... ('zrq', 'zxy') ('zrq', 'hello') ('zrq', 'world') ('zxy', 'hello') ('zxy', 'world') ('hello', 'world' 比起实用技术来说这是一个很有趣的事,在python中,True和False是全局变量,因此:
False = True
if False:
print "Hello"
else:
print "World"
>>> Hello
|