符合语言习惯的 Python 优雅编程技巧

  • 时间:
  • 浏览:1
  • 来源:uu快3官方邀请码_uu快3app赚钱_彩神8

pass##推荐from contextlib import ignored # Python 3 only

# ....if len(items) != 0:

with ignored(OSError):

# ...if items != []:

lock.acquire()

# 但会 使用 setdefault 辦法 navs.setdefault(portfolio, 0)

##推荐 colors = ['red', 'blue', 'green', 'yellow']

# 互斥操作...finally:

##推荐 navs = {}

# ....if items:

http://www.python.org/dev/peps/pep-0008/

“Programs must be written for people to read, and only incidentally for machines to execute.”

##推荐with open("some_file.txt") as f:

# my_dict[key] ...# 必须当循环中需用更改key值的具体情况下,大伙儿需用使用 my_dict.keys()# 生成静态的键值列表。

def setHour(self, hour):if 25 > hour > 0: self.__hour = hour

http://python.net/~goodger/projects/pycon/10007/idiomatic/handout.html

# ... ##推荐if x:

2) PEP 8: Style Guide for Python Code:

# do something for x & y ##推荐from itertools import product

Python最大的优点之一就说 语法简洁,好的代码就像伪代码一样,干净、整洁、一目了然。要写出 Pythonic(优雅的、地道的、整洁的)代码,需用多看过学大牛们写的代码,github 上有或多或少非常优秀的源代码值得阅读,比如:requests、flask、tornado,下面列举或多或少常见的Pythonic写法。

# do something for x, y, z

# 互斥操作...

# my_dict[key] ... ##推荐for key in my_dict:

with lock:

# 或多或少文件操作...

# ...do something with d[key] ##推荐if key in my_dict:

def getHour(self):return self.__hour

# 使用 get 辦法 navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]

##推荐def my_range(n): i = 0

result = ''

# method 1 i = 0

# 使用 in 更加简洁

# do something...

# do something... ##推荐 gen = (item for sl in nested_list if list_condition(sl) \

class Clock(object):def __init__(self): self.__hour = 1

# ...do something with d[key]

##推荐import threading

def my_range(n): i = 0

# 多次判断 ##推荐if fruit in ["apple", "orange", "berry"]:

##推荐 new_list = [fn(item) for item in a_list if condition(item)]

##推荐 l = ['David', 'Pythonista', '+1-514-555-1234']

# do something if found...

原文发布时间为:2018-11-15

##推荐from itertools import ifilter, imap

本文作者:安生

# do something if found... ##推荐if any(condition(item) for item in a_list):

# method 2for i in range(len(items)):

##推荐class Clock(object):def __init__(self): self.__hour = 1

##推荐 a, b = b, a # 先生成一个多 多元组(tuple)对象,但会 unpack

##推荐 items = 'zero one two three'.split()

breakif found:

# ...

# Python 3 Only first, *middle, last = another_list

1) Idiomatic Python:

def __setHour(self, hour):if 25 > hour > 0: self.__hour = hour

# 或多或少文件操作..finally:

def __getHour(self):return self.__hour