server = HTTPServer(('', 8000), RequestHandler) server.serve_forever()
或
1
python3 -m http.server 8000
一行Python代码可以做什么
很多时候,你的问题只需一行Python代码就能解决。
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# 一行代码实现求阶乘函数 fac = lambda x: __import__('functools').reduce(int.__mul__, range(1, x + 1), 1)
# 一行代码实现求最大公约数函数 gcd = lambda x, y: y % x and gcd(y % x, x) or x
# 一行代码实现判断素数的函数 is_prime = lambda x: x > 1andnot [f for f inrange(2, int(x ** 0.5) + 1) if x % f == 0]
# 一行代码实现快速排序 quick_sort = lambda items: len(items) and quick_sort([x for x in items[1:] if x < items[0]]) + [items[0]] + quick_sort([x for x in items[1:] if x > items[0]]) or items
# 生成FizzBuzz列表 ['Fizz'[x % 3 * 4:] + 'Buzz'[x % 5 * 4:] or x for x inrange(1, 101)]
设计模式从未如此简单
Python是动态类型语言,大量的设计模式在Python中被简化或弱化。
思考:如何优化下面的代码。
1 2 3 4
deffib(num): if num in (1, 2): return1 return fib(num - 1) + fib(num - 2)
代理模式在Python中可以通过内置的或自定义的装饰器来实现。
1 2 3 4 5 6 7 8 9 10 11 12
from functools import lru_cache
@lru_cache() deffib(num): if num in (1, 2): return1 return fib(num - 1) + fib(num - 2)
for page inrange(10): resp = requests.get( url=f'https://movie.douban.com/top250?start={25 * page}', headers={'User-Agent': 'BaiduSpider'} ) soup = BeautifulSoup(resp.text, "lxml") for elem in soup.select('a > span.title:nth-child(1)'): print(elem.text) time.sleep(random.random() * 5)
利用NumPy、Pandas、Matplotlib可以轻松实现数据分析和可视化。
写出Python代码的正确姿势
用Python写代码就要写出Pythonic的代码。
姿势1:选择结构的正确姿势
跨界开发者的代码:
1 2 3 4 5
name = 'jackfrued' fruits = ['apple', 'orange', 'grape'] owners = {'name': '骆昊', 'age': 40, 'gender': True} if name != ''andlen(fruits) > 0andlen(owners.keys()) > 0: print('Jackfrued love fruits.')
Pythonic的代码:
1 2 3 4 5
name = 'jackfrued' fruits = ['apple', 'orange', 'grape'] owners = {'name': '骆昊', 'age': 40, 'gender': True} if name and fruits and owners: print('Jackfrued love fruits.')
姿势2:交换两个变量的正确姿势
跨界开发者的代码:
1 2 3
temp = a a = b b = temp
或
1 2 3
a = a ^ b b = a ^ b a = a ^ b
Pythonic的代码:
1
a, b = b, a
姿势3:用序列组装字符串的正确姿势
跨界开发者的代码:
1 2 3 4
chars = ['j', 'a', 'c', 'k', 'f', 'r', 'u', 'e', 'd'] name = '' for char in chars: name += char
fruits = ['orange', 'grape', 'pitaya', 'blueberry'] index = 0 for fruit in fruits: print(index, ':', fruit) index += 1
Pythonic的代码:
1 2 3
fruits = ['orange', 'grape', 'pitaya', 'blueberry'] for index, fruit inenumerate(fruits): print(index, ':', fruit)
姿势5:创建列表的正确姿势
跨界开发者的代码:
1 2 3 4 5
data = [7, 20, 3, 15, 11] result = [] for i in data: if i > 10: result.append(i * 3)
Pythonic的代码:
1 2
data = [7, 20, 3, 15, 11] result = [num * 3for num in data if num > 10]
姿势6:确保代码健壮性的正确姿势
跨界开发者的代码:
1 2 3 4 5 6 7
data = {'x': '5'} if'x'in data andisinstance(data['x'], (str, int, float)) \ and data['x'].isdigit(): value = int(data['x']) print(value) else: value = None
Pythonic的代码:
1 2 3 4 5 6
data = {'x': '5'} try: value = int(data['x']) print(value) except (KeyError, TypeError, ValueError): value = None
classPoker(object): def__init__(self): self.cards =[Card(suite, face) for suite in Suite for face inrange(1, 14)] self.current=0 defshuffle (self): self.current=0 random.shuffle(self.cards) defdeal (self): card = self.cards[self.current] self.current+=1 return card defhas_next (self): if self.current<len(self.cards): returnTrue returnFalse
p = Poker() p.shuffle() print(p.cards)
PyLint的安装和使用
Pylint是Python代码分析工具,它分析Python代码中的错误,查找不符合代码风格标准(默认使用的代码风格是 PEP 8)和有潜在问题的代码。