博客链接
如何优美的书写python代码
ymdstr = datetime.date.today().strftime("%y-%m-%d")
current_date: str = datetime.date.today().strftime("%y-%m-%d")
get_user_info()
get_client_data()
get_customer_record()
get_user_info()
get_user_data()
get_user_record()
class User:
info : str
@property
def data(self) -> dict:
# ...
def get_record(self) -> Union[Record, None]:
# ...
大部分时间你都是在读代码而不是写代码,所以我们写的代码可读且可被搜索尤为重要,一个没有名字的变量无法帮助我们理解程序,也伤害了读者,记住:确保可搜索。
time.sleep(86400);
# 在全局命名空间声明变量,一天有多少秒
SECONDS_IN_A_DAY = 60 * 60 * 24
time.sleep(SECONDS_IN_A_DAY)
matches = re.match(r'正则匹配', address)
zip_code(matches[1], matches[2]) # 看不懂什么意思
matches = re.match(r'正则匹配', address)
city, zip_code = matches.groups() # 清晰明了
zip_code(city, zip_code)
seq = ('Austin', 'New York', 'San Francisco')
for item in seq:
do_stuff()
do_some_other_stuff()
# ...
# Wait, what's `item` for again?
dispatch(item)
locations = ('Austin', 'New York', 'San Francisco')
for location in locations:
do_stuff()
do_some_other_stuff()
# ...
dispatch(location)
class Car:
car_make: str
car_model: str
car_color: str
class Car:
make: str
model: str
color: str
def create_micro_brewery(name):
name = "Hipster Brew Co." if name is None else name
slug = hashlib.sha1(name.encode()).hexdigest()
# etc.
def create_micro_brewery(name = "Hipster Brew Co."): # 直接设置默认值
slug = hashlib.sha1(name.encode()).hexdigest()
# etc.
tmp = a
a = b
b = tmp
a, b = b, a
numbers = []
for x in xrange(20):
if x % 3 == 0:
numbers.append(x*x)
numbers = [x*x for x in range(20) if x % 3 == 0]
# 集合
numbers = {x * x for x in range(0, 20) if x % 3 == 0}
# 字典
numbers = {x: x * x for x in range(0, 20) if x % 3 == 0}
words = ['I', ' ', 'love', ' ', 'Python', '.']
sentence = ''
for word in words:
sentence += '' + word
words = ['I', ' ', 'love', ' ', 'Python', '.']
sentence = ''.join(words)
a = 'I love Python.'
reverse_a = ''
for i in range(0, len(a)):
reverse_a += a[len(a) - i - 1]
a = 'I love Python.'
reverse_a = a[::-1]
cities = ['BeiJing', 'TianJin', 'JiNan', 'ShenZhen', 'WuHan']
tofind = 'Shanghai'
found = False
for city in cities:
if tofind == city:
print 'Found!'
found = True
break
if not found:
print 'Not found!'
cities = ['BeiJing', 'TianJin', 'JiNan', 'ShenZhen', 'WuHan']
tofind = 'Shanghai'
for city in cities:
if tofind == city:
print 'Found!'
break
else:
# 执行else中的语句意味着没有执行break
print 'Not found!'
cities = ['BeiJing', 'TianJin', 'JiNan', 'ShenZhen', 'WuHan']
index = 0
for city in cities:
index = index + 1
print index, ':', city
cities = ['BeiJing', 'TianJin', 'JiNan', 'ShenZhen', 'WuHan']
for index, city in enumerate(cities, 1):
print index, ":", city
def f(x):
return x * x
map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9])
# 普通情况
def f(x):
return x * x
# 等价于
lambda x: x * x
装饰器在Python中应用特别广泛,其特点是可以在具体函数执行之前或者之后做相关的操作,比如:执行前打印执行函数的相关信息,对函数的参数进行校验;执行后记录函数调用的相关流水日志等。使用装饰器最大的好处是使得函数功能单一化,仅仅处理业务逻辑,而不附带其它功能。
from time import ctime
def foo():
print('[%s] %s() is called' % (ctime(), foo.__name__))
print('Hello, Python')
from time import ctime
def deco(func):
def decorator(*args, **kwargs):
print('[%s] %s() is called' % (ctime(), func.__name__))
return func(*args, **kwargs)
return decorator
@deco
def foo():
print('Hello, Python')
生成器与列表最大的区别就是,列表是一次性生成的,需要较大的内存空间;而生成器是需要的时候生成的,基本不占用内存空间。生成器分为生成器表达式和生成器函数。
先看一下列表:
l = [x for x in range(10)]
改为生成器只需要将[…]变为(…),即生成器表达式
g = (x for x in range(10))
至于生成器函数,是通过yield关键字来实现的,我们以计算斐波那契数列为例,使用列表可以用如下代码来实现:
def fib(max):
n, a, b = 0, 0, 1
fibonacci = []
while n < max:
fibonacci.append(b)
a, b = b, a + b
n = n + 1
return fibonacci
生成器
def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
通常的词频统计中,我们的思路是:
需要一个字典,key值存储单词,value存储对应的词频。当遇到一个单词,判断是否在这个字典中,如果是,则词频加1;如果否,则字典中新增这个单词,同时对应的词频设置为1。
wordList 是一个列表 [‘足球’,‘篮球’,‘乒乓球’,‘足球’…]
#统计单词出现的频次
def computeFrequencies(wordList):
#词频字典
wordfrequencies = {}
for word in wordList:
if word not in wordfrequencies:
# 单词不在单词词频字典中, 词频设置为1
wordfrequencies[word] = 1
else:
# 单词在单词词频字典中, 词频加1
wordfrequencies[word] = wordfrequencies[word] + 1
return wordfrequencies
# 统计单词出现的频次
def computeFrequencies(wordList):
#词频字典
wordfrequencies = Counter(wordList)
return wordfrequencies
博客链接