python技巧
python语言是一门很灵活的语言,有很多方便的内置函数(比如map,reduce,iter,enumerate,all,zip,upper等等)和魔法方法,支持级联还有三元运算等,它的特性决定了它可以简化程序员的一些操作,但是掌握这些技巧的关键在于灵活应用,还有,前提是你记得住。下面罗列一些python的小技巧:
浮点运算
>print .3//.2
1.0
强制浮点
>from __future__ import division
>res=1/2
0.5
if嵌入到语句内
print "right" if 1==2 else "wrong"
isinstance接收元组
isinstance可以判断数据的类型,实际上,它可以接收元组
isinstance(2.0,(int,long,float))
重定向输出内容到文件
print >> open("filename","w+"),"hello world"
这样hello world就输出到filename这个文件内
关键字格式化
>print "Hello %(name)" % {'name':'world'}
Hello world
拼接
>a=[“hello”,"jack”]
>b=[“hi”,"lucy”]
>print a+b
[“hello”,”jack”,”hi”,”lucy”]
>print str(python)+"good”
pythongood
>print `python` + “good”
pythongood
>print python,good
pythongood
>print a,"good”
[‘hello’, ‘jack’]good
同时迭代两个列表
>>> a=["bob","mike"]
>>> b=["tony","jake"]
>>> for a,b in zip(a,b):
print a+" vs "+b
bob vs tony
mike vs jake
索引
>>> aa=['a','b','c','d']
>>> list(enumerate(aa,2))
[(2, 'a'), (3, 'b'), (4, 'c'), (5, 'd')]
索引迭代
>>> a=["bob","mike","tony"]
>>> for index,name in enumerate(a):
print index,name
0 bob
1 mike
2 tony
获取列表内偶数数据
>>> nums=[1,4,6,8,6]
>>> even=[num for num in nums if num%2==0]
>>> print even
[4, 6, 8, 6]
字典获取键或值(出错返回False)
data = {'user': 1, 'name': 'tony', 'id': 4}
try:
aa=data['user']
except:
aa=False
可以简化为:
data = {'user': 1, 'name': 'tony', 'id': 4}
aa=data.get('user',False)
字典键的推导:
>a=["hello","hi","find"]
>print {key : value for value,key in enumerate(a)}
{'hi': 1, 'hello': 0, 'find': 2}
实现字符串反转的方法:
str=”hello”
def reverse1(str):
return str[::-1]
def reverse2(str): #递归
if str==””:
return str
else:
return reverse2(str[1:]) +str[0]
/*
def reverse3(str):
t=list(str)
l=len(t)
for i,j in zip(range(l-1,0,-1),range(1//2)):
t[i],t[j]=t[j],t[i]
return “”.join(t)
*/
def reverse4(str):
return ‘’.join(str[i] for i in range(len(str)-1,-1,-1))
from collections import deque
def reverse5(str):
d=deque()
d.extendleft(str)
return ‘’.join(d)
字典的反转:
比如>m={‘a’:1,’b’:2,’c’:3}
法1:
{ i:j for j,i in m.items()}
法2:
>m.items()
[(‘a’,1),(‘c’:3),(‘b’,2)]
>zip(m.values(),m.keys())
[(1,’a’),(3,’c’),(2,’b’)]
>m== dict(zip(m.values(), m.keys()))
>m
{1: 'a', 2: 'b', 3: 'c'}
手动输入字符串,转换为列表(输入的时候中间要有空格)
>res=map(lambda x:int(x),raw_input().split())
1 2 3
>res
[1,2,3]
map函数:
>def add(x):
return x+1
>num=[1,2,3]
>map(add,num)
[2,3,4]
类似c语言数组指针函数
lambda:
>g=lambda x,y:x+y
>g(1,2)
3
列表和迭代器的压缩和解压缩、转置
>>> a = [1, 2, 3]
>>> b = ['a', 'b', 'c']
>>> z = zip(a, b)
>>> z
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> zip(*z)
[(1, 2, 3), ('a', 'b', 'c')]
列表展开:
>a = [[1, 2], [3, 4], [5, 6]]
>sum(a,[])
[1,2,3,4,5,6]
>[x for l in a for x in l]
[1, 2, 3, 4, 5, 6]
字典推导
>m={x:x**2 for x in range(3)}
>m
{0: 0, 1: 1, 2: 4}
>m={x:'A'+ str(x) for x in range(3)}
>m
{0: 'A0', 1: 'A1', 2: 'A2'}
统计在可迭代对象中常见的元素
>>> A = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7])
>>> A
Counter({3: 4, 1: 2, 2: 2, 4: 1, 5: 1, 6: 1, 7: 1})
>>> A.most_common(1)
[(3, 4)]
>>> A.most_common(3)
[(3, 4), (1, 2), (2, 2)]
参考:http://blog.jobbole.com/63320/
http://litaotao.github.io/python-materials