python风格代码荟萃

今天总结一下在python中常用的一些风格代码,这些可能大家都会用,但有时可能也会忘记,在这里总结,工大家参考~~~

先点赞在看,养成习惯~~~

标题遍历一个范围内的数字

for i in xrange(6):
    print i ** 2

xrange会返回一个迭代器,用来一次一个值地遍历一个范围,这种方式比range更省内存。在python3中xrange已经改名为range。

遍历集合

colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
    print color

反向遍历集合

for color in reversed(colors):
    print color

遍历集合及其下标

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

遍历两个集合

names = ['raymond', 'rachel', 'mattthew']
colors = ['red', 'green', 'blue', 'yellow']
for name, color in izip(names, colors):
    print name, '-->', color

zip在内存中生成一个新的列表,需要更多的内存,izip比zip效率更高。在python3中,izip改名为zip,替换了原来的zip成为内置函数。

有序遍历

colors = ['red', 'green', 'blue', 'yellow']
for color in sorted(colors):
    print color
for color in sorted(coloes, reverse = True):
    print color

自定义排序顺序

colors = ['red', 'green', 'blue', 'yellow']
print sorted(colors, key=len)

列表解析和生成器

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

在循环内识别多个退出点

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

分离临时上下文

with open('help.txt', 'w') as f:
    with redirect_stdout(f):
        help(pow)

上述代码用于演示如何临时把标准输出重定向到一个文件,然后再恢复正常。注意redirect_stdout在python3.4加入。

打开关闭文件

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

使用锁

lock = threading.Lock()
with lock:
    print 'critical section 1'
    print 'critical section 2'

用字典计数

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

d = {
    
    }
for color in colors:
    d[color] = d.get(color, 0) + 1

d = defaultdict(int)
for color in colors:
    d[color] += 1

资源传送门

  1. 关注【做一个柔情的程序猿】公众号
  2. 在【做一个柔情的程序猿】公众号后台回复 【python资料】【2020秋招】 即可获取相应的惊喜哦!

「❤️ 感谢大家」

  • 点赞支持下吧,让更多的人也能看到这篇内容(收藏不点赞,都是耍流氓 -_-)
  • 欢迎在留言区与我分享你的想法,也欢迎你在留言区记录你的思考过程。

猜你喜欢

转载自blog.csdn.net/ywsydwsbn/article/details/108900272
今日推荐