如何写出更 pythonic 的 Python 代码

2019-01-06  本文已影响0人  v1coder
a, b = b, a

列表推导式

l = [x*x for x in range(10) if x % 3 == 0]
#l = [0, 9, 36, 81]

还有字典和集合的推导式

生成器是可迭代对象,但在每次调用时才产生一个结果,而不是一次产生整个结果。

squares = (x * x for x in range(10))
with open('filename') as f:
    data = file.read()

with 相比于一般的 open、close 有异常处理,并能保证关闭文件。相比于 try…finally 代码更简洁。

0 < a < 10
name = 'v1coder'
if name:

# 而不是
if name != '':

即,对于任意对象,直接判断其真假,无需写判断条件

真假值表

def reverse_str( s ):
    return s[::-1] 
str_list = ["Python", "is", "good"]  
 
res =  ' '.join(str_list) #Python is good
for x in xrange(1,5):
    if x == 5:
        print 'find 5'
        break
else:
    print 'can not find 5!'

如果循环全部遍历完成,没有执行 break,则执行 else 子句

numList = [1,2,3,4,5]   
 
sum = sum(numList)
maxNum = max(numList)
minNum = min(numList)
choices = ['pizza', 'pasta', 'salad', 'nachos']

for index, item in enumerate(choices):
  print(index, item)

# 输出:
0 pizza
1 pasta
2 salad
3 nachos
dict = {'Google': 'www.google.com', 'Runoob': 'www.runoob.com', 'taobao': 'www.taobao.com'}
 
print "字典值 : %s" %  dict.items()
 
for key,values in  dict.items():
    print key,values

# 输出:
字典值 : [('Google', 'www.google.com'), ('taobao', 'www.taobao.com'), ('Runoob', 'www.runoob.com')]
Google www.google.com
taobao www.taobao.com
Runoob www.runoob.com
dict = {'Name': 'Zara', 'Age': 27}

print(dict.get('Age'))
print(dict.get('Sex', "Never"))

# 输出:
27
Never

用 get 方法,不存在时会得到 None,或者指定的默认值。


pythonic 可以理解为Python 式的优雅,简洁、明了,可读性高。


PEP 8 -- Style Guide for Python Code
Python语言规范 - Google
Pythonic 是什么意思?

上一篇 下一篇

猜你喜欢

热点阅读