大佬的编码建议,让你的代码更pythonic

Raymond Hettinger是 Python 核心开发者,本文提到的许多特性都是他开发的。

若无例外,本文代码中出现的 colors names d 等变量全为以下所定义,其中, colors names 为列表,d 为字典。且本文所说的集合全都指 collection ,而不是 set 。

colors = ['red', 'green', 'blue', 'yellow']
names = ['raymond', 'rachel', 'matthew']
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}

遍历一个集合

for color in colors:
print(color)

反向遍历

for color in reversed(colors):
print(color)

遍历一个集合及其下标

for i, color in enumerate(colors):
print(i, '--->', color)

遍历两个集合

for name, color in zip(names, colors):
print(name, '--->', color)

有序地遍历

# 正序
for color in sorted(colors):
print(color) # 倒序
for color in sorted(colors, reverse=True):
print(color)

自定义排序顺序

def compare_length(c1, c2):
if len(c1) < len(c2): return -1
if len(c1) > len(c2): return1
return0 print(sorted(colors, cmp=compare_length)) print(sorted(colors, key=len)) # 更好的选择

调用一个函数直到遇到标记值

 blocks = []
for block in iter(partial(f.read, 32), ''):
blocks.append(block)

iter 接受两个参数。第一个是你反复调用的函数,第二个是标记值。

优势在于 iter 的返回值是个迭代器,迭代器能用在各种地方,set,sorted,min,max,heapq,sum……

在循环内识别多个退出点 for-else 语法

def find(seq, target):
for i, value in enumerate(seq):
if value == target:
break
else:
return -1
return i

for 执行完所有的循环后就会执行 else 。且 for 循环中没有 退出.

遍历字典的key

# 方法一
for k in d:
print(k) # 方法二
for k in list(d.keys()):
if k.startswith('r'):
del d[k]

需要修改字典的时候使用第二种方法

d.keys() 把字典里所有的 key 都复制到一个列表里。然后你就可以修改字典了。

遍历一个字典的key和value

for k, v in d.items():
print(k, '--->', v)

用key-value对构建字典

names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue'] d = dict(zip(names, colors))
# {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}

用字典计数

colors = ['red', 'green', 'red', 'blue', 'green', 'red']

# 方法一
d = {}
for color in colors:
d[color] = d.get(color, 0) + 1 # 稍微潮点的方法,但有些坑需要注意,适合熟练的老手。
from collections import defaultdict
d = defaultdict(int)
for color in colors:
d[color] += 1

用字典分组 — 第I部分和第II部分

# 在这个例子,我们按name的长度分组
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie'] from collections import defaultdict
d = defaultdict(list)
for name in names:
key = len(name)
d[key].append(name)

字典的popitem()是原子的吗?

d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
while d:
key, value = d.popitem()
print(key, '-->', value)

popitem 是原子的,所以多线程的时候没必要用锁包着它。

连接字典

import os
import argparse
from collections import ChainMap
defaults = {'color': 'red', 'user': 'guest'}
parser = argparse.ArgumentParser()
parser.add_argument('-u', '--user')
parser.add_argument('-c', '--color')
namespace = parser.parse_args([])
command_line_args = {k: v for k, v in vars(namespace).items() if v} d = ChainMap(command_line_args, os.environ, defaults)

用namedtuple提高多个返回值的可读性

# namedtuple是tuple的子类,所以仍适用正常的元组操作,但它更友好。
TestResults = namedTuple('TestResults', ['failed', 'attempted'])

unpack序列

p = 'Raymond', 'Hettinger', 0x30, 'python@example.com'
fname, lname, age, email = p

更新多个变量的状态

def fibonacci(n):
x, y = 0, 1
for i in range(n):
print(x)
x, y = y, x + y

同时状态更新

x, y, dx, dy = (x + dx * t,
y + dy * t,
influence(m, x, y, dx, dy, partial='x'),
influence(m, x, y, dx, dy, partial='y'))

连接字符串

names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
print(', '.join(names))

更新序列

from collections import deque
names = ['raymond', 'rachel', 'matthew', 'roger',
'betty', 'melissa', 'judith', 'charlie']
names = deque(names)

用deque更有效率

del names[0]
names.popleft()
names.appendleft('mark')

如何打开关闭文件

with open('data.txt') as f:
data = f.read()

如何使用锁

# 创建锁
lock = threading.Lock()
with lock:
print('Critical section 1')
print('Critical section 2')

列表解析和生成器

print(sum(i**2for i in xrange(10)))

大佬的编码建议,让你的代码更pythonic的更多相关文章

  1. Python 有哪些优雅的代码实现让自己的代码更pythonic?

    https://www.zhihu.com/question/37751951/answer/73425339 https://www.cnblogs.com/geaozhang/p/7111961. ...

  2. iOS开发编码建议与编程经验

    作者:乞力马扎罗的雪(GitHub) 原文 在开发过程中,我们不仅要去看别人的代码,也要让别人看我们的代码.那么,有一个良好的编码习惯将会非常重要.下面将会罗列使用Objective-C来开发iOS的 ...

  3. 怎样让你的代码更好的被JVM JIT Inlining

    好书推荐:Effective Java中文版(第2版) JVM JIT编译器优化技术有近100中,其中最最重要的方式就是内联(inlining).方法内联可以省掉方法栈帧的创建,方法内联还使让JIT编 ...

  4. JDK8漫谈——代码更优雅

    简介 lambda表达式,又称闭包(Closure)或称匿名方法(anonymous method).将Lambda表达式引入JAVA中的动机源于一个叫"行为参数"的模式.这种模式 ...

  5. CSS 黑魔法小技巧,让你少写不必要的JS,代码更优雅

    首页   登录注册         CSS 黑魔法小技巧,让你少写不必要的JS,代码更优雅 阅读 8113 收藏 927 2017-09-26 原文链接:github.com 腾讯云容器服务CSS,立 ...

  6. 让 Python 代码更易维护的七种武器——代码风格(pylint、Flake8、Isort、Autopep8、Yapf、Black)测试覆盖率(Coverage)CI(JK)

    让 Python 代码更易维护的七种武器 2018/09/29 · 基础知识 · 武器 原文出处: Jeff Triplett   译文出处:linux中国-Hank Chow    检查你的代码的质 ...

  7. 用Assert(断言)封装异常,让代码更优雅(附项目源码)

    有关Assert断言大家并不陌生,我们在做单元测试的时候,看业务事务复合预期,我们可以通过断言来校验,断言常用的方法如下: public class Assert { /** * 结果 = 预期 则正 ...

  8. 可爱的豆子——使用Beans思想让Python代码更易维护

    title: 可爱的豆子--使用Beans思想让Python代码更易维护 toc: false comments: true date: 2016-06-19 21:43:33 tags: [Pyth ...

  9. 基于AOP的MVC拦截异常让代码更优美

    与asp.net 打交道很多年,如今天微软的优秀框架越来越多,其中微软在基于mvc的思想架构,也推出了自己的一套asp.net mvc 框架,如果你亲身体验过它,会情不自禁的说‘漂亮’.回过头来,‘漂 ...

随机推荐

  1. 使用Apache IO库操作IO与文件

    --------------siwuxie095                         首先到 Apache官网 下载相关的库文件     Apache官网:http://www.apach ...

  2. 关于windows的锁定状态

    本来以为要在项目里用上的,现在看来不需要了,把相关的函数列一下吧,以后如果用到了,再写详细点 锁定计算机 : LockWorkStation 注册Windows状态变化的监听函数: BOOL WTSR ...

  3. 345. Reverse Vowels of a String翻转字符串中的元音字母

    [抄题]: Write a function that takes a string as input and reverse only the vowels of a string. Example ...

  4. 性能优化之_android布局优化

    优化布局的的原则就是减少创建的对象的数量,setContentView话费onCreate到onResume中的大概99%的时间1.使用Relativelayout而不是LinearLayout,Li ...

  5. 数字图像处理实验(14):PROJECT 06-01,Web-Safe Colors 标签: 图像处理MATLAB 2017-05-27 20:45 116人阅读

    实验要求: Objective: To know what are Web-safe colors, how to generate the RGB components for a given jp ...

  6. Django rest_framework----序列化组件

    生成hypermedialink serializer.pclass BookModelSerializers(serializers.ModelSerializer): class Meta: mo ...

  7. ubuntu 14.04编译安装xen4.4总结

    1. 安装环境 操作系统:ubuntu14.04 xen版本:xen4.4 2. 依赖包的安装 在安装xen之前先进行依赖包的安装,在不停得尝试之后,总结出以下需要安装的依赖包. sudo apt-g ...

  8. easyui-dialog 弹窗

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/ ...

  9. 20169219 使用Metaspoit攻击MS08-067实验报告

    MS08-067漏洞介绍 MS08-067漏洞的全称为"Windows Server服务RPC请求缓冲区溢出漏洞",如果用户在受影响的系统上收到特制的 RPC 请求,则该漏洞可能允 ...

  10. 享元(Flyweight)模式

    享元(Flyweight)模式:运用共享技术有效的支持大量细粒度的对象. /* * 抽象享元(Flyweight)角色:此角色是所有的具体享元类的超类,为这些类规定出需要实现的公共接口. 那些需要外蕴 ...