什么是pythonic?pythonic翻译成中文来讲就是很python
。很+名词
结构的用法在日常用语中很常见。例如:很娘。日常用语中,很+名词
结构的用语带便了强调和加强的意味。所以pythonic
在我个人的理解就是:只有python能够做到的,代码更加简明,优雅,执行效率更高。
例如,一个很常见的置换两个变量的值:
python:
a,b = b,a
非python:
temp = a
a = b
b = temp
上面的列子可以很好的看出python的优势及特点,这就是pythonic,当然python也可以使用非python的那种写法,不过那就不符合pythonic
的理念了。
我们常常会用如下方法:
l = [0,1,2,3,4]
for i in l:
print i
或者:
for i in range(5):
print i
pythonic写法:
for i in xrange(5):
print i
xrange会生成一个迭代器,用来一次一个值的遍历一个范围。这种方式会比range更加节省内存。xrange在python 3.x中已经更名为range
我们常常会用如下方法:
l = ["江西","广东","江苏","福建","湖南"]
for i in range(len(l) - 1, -1, -1):
print i
pythonic写法:
l = ["江西","广东","江苏","福建","湖南"]
for i in reversed(l):
print i
我们常常会用如下方法:
l = ["江西","广东","江苏","福建","湖南"]
for i in range(len(l)):
print i,l[i]
pythonic写法:
l = ["江西","广东","江苏","福建","湖南"]
for i,value in enumerate(l):
print i,value
下面这种写法更加高效,更加优雅,而且帮你省去了自己创建下标和获取相应的值。
我们常常会用如下方法:
l1 = ["江西","广东","江苏","福建","湖南"]
l2 = ["南昌","广州","南京","福州","长沙"]
for province,city in zip(l1,l2):
print province,city
pythonic写法:
l1 = ["江西","广东","江苏","福建","湖南"]
l2 = ["南昌","广州","南京","福州","长沙"]
for province,city in izip(l1,l2):
print province,city
izip为itertools中的一个方法。zip在内存中会生成一个新的列表,需要更多的内存。izip相比较于zip效率更高。在python 3.x中,izip更名为zip,替换了原来的zip成为了python 的内置函数。
例如我们需要获取一个列表中,每个元素的个数,并生成一个字典:
l = ["江西","广东","江苏","福建","湖南","江西","福建","江苏"]
我们常常会用如下方法:
d = {}
for item in l:
if item not in d.keys():
d[item] = 0
d[item] += 1
pythonic写法:
d = {}
for item in l:
d[item] = d.get(item,0) + 1
# 或者这样
from collections import defaultdict
d = defaultdict(int)
for item in l:
d["item"] += 1
例如有这样一个需求,需要遍历一个字典的键与值:
d = {"province":"广东","city":"深圳"}
我们常常会用如下方法:
for item in d:
print item,d[item]
# 或者这样
for key,value in d.items():
print key,value
pythonic写法:
for key,value in d.iteritems():
print key,value
使用pythonic
写法是因为iteritems
返回的是一个迭代器。注意: python 3.x中已经没有了iteritems,items中的行为已经跟iteritems很接近了。
例如有这样一个需求,需要将以下列表的元素以长度进行分组:
l = ["red","green","blue","yellow","black","pink","grey"]
我们常常会用如下方法:
d = {}
for item in l:
key = len(item)
if key not in d:
d[key] = []
d[key].append(item)
print d # {3: ['red'], 4: ['blue', 'pink', 'grey'], 5: ['green', 'black'], 6: ['yellow']}
# 或者这样
d = {}
for item in l:
key = len(item)
d.setdefault(key,[]).append(item)
print d # {3: ['red'], 4: ['blue', 'pink', 'grey'], 5: ['green', 'black'], 6: ['yellow']}
pythonic写法:
from collections import defaultdict
d = defaultdict(list)
for item in l:
key = len(item)
d[key].append(item)
例如有这样一个需求,需要将以下列表的元素连接成一个新的字符串:
l = ["h","e","l","l","o"]
我们常常会用如下方法:
s = l[0]
for item in l[1:]:
s += item
print s
pythonic写法:
print "".join(l)
例如有这样一个需求,需要将以下列表的元素进行增删操作:
l = ["哈哈","呵呵","嘿嘿"]
我们常常会用如下方法:
del l[0]
l.pop(0)
l.insert(0,"哼哼")
pythonic写法:
from collections import deque
l = deque(l)
del l[0]
l.popleft()
l.appendleft("哼哼")
为什么要用deque
呢,因为deque更有效率