Beautiful, Idiomatic Python (一)

零、Prepare Jupyter notebook

  • 安装配置虚拟环境
$ pip install virtuanlenv
$ virtualenv ENV
$ cd ENV
$ source bin/activate
$ pip install jupyter
$ jupyter notebook
  • Jupyter notebook

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more.

一、Practice makes perfect

"Flat is better than nested" - The Zen of Python

##Looping over a range of numbers
for i in range(6):
    print(i**2)
##Looping over a collection
colors = ['red', 'green', 'blue', 'yellow']
for color in colors:
    print (color)
##Looping over a collection
for i in range(len(colors)):
    print (colors[i])
##Looping backwards
for color in reversed(colors):
    print(color)
##Looping over a collection and indices
for i, color in enumerate(colors):
    print(i, '-->', color)
##Looping over two collections
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue', 'yellow']

for name, color in zip(names, colors):
    print(name,'-->','color')
    
##Looping in sorted order
colors = ['red', 'green', 'blue', 'yellow']

for color in sorted(colors):
    print(color)
for color in sorted(colors, reverse=True):
    print(color)
##Custom Sort Order
print(sorted(colors, key=len))
##Call a function until a sentinel value
blocks = []
while True:
    block = f.read(32)
    if block == '':
        break
    blocks.apeend(block)
    
##Better
blocks=[]
for block in iter(partial(f.read, 32),''):
    blocks.append(block)
##Distinguishing multiple exit points in loops
def find(seq, target):
    found = False
    for i, value in enumerate(seq):
        if value == target:
            found =True
            break
    if not found:
        return -1
    return i


## Better
def find(seq, target):
    for i, value in enumerate(seq):
        if value == target:
            break
    else:    ##Inside of every for loop is an else.
        return -1
    return i
##Looping over dictionary keys
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'} 
for k in d:
    print(k) 
for k in d:
    print(k,'-->',d[k])
    
for k, v in d.items(): ## Makes a hug list
    print(k,'-->',v)
##Construct a dictionary from pairs
names = ['raymond', 'rachel', 'matthew']
colors = ['red', 'green', 'blue']

d = dict(zip(names, colors))

##Counting with dictionaries
colors = ['red', 'green', 'red', 'blue', 'green', 'red']
d = {}
for color in colors:
    if color not in d:
        d[color] = 0
    d[color] +=1
##Better
x = {}
for color in colors:
    x[color] = x.get(color,0) + 1

##Grouping with dictionaries
names = ['raymond', 'rachel', 'matthew', 'roger',
         'betty', 'melissa', 'judith', 'charlie']
##group by name,length
d = {}
for name in names:
    key = len(name)
    if key not in d:
        d[key] = []
    d[key].append(name)

x = {}
for name in names:
    key = len(name)
    x.setdefault(key,[]).append(name)
    
##Better
from collections import defaultdict
d = defaultdict(list)
for name in names:
    key = len(name)
    d[key].append(name)

##Is a dictionary popitem() atomic?
d = {'matthew': 'blue', 'rachel': 'green', 'raymond': 'red'}
while d:
    key,value = d.popitem()
    print(key,'-->',value)

##List Comprehensions and Generator Expressions
result = []
for i in range(10):
    s = i**2
    result.append(s)
print(sum(result))

##Better
print(sum(i**2 for i in range(10)))
##How to open and close files
f = open('data.txt')
try:
    data = f.read()
finally:
    f.close()

## Better
with open('data.txt') as f:
    data = f.read()
##Using decorators to factor-out administrative logic
def web_lookup(url, saved={}):
    if url in saved:
        return saved[url]
    page = urllib.urlopen(url).read()
    saved[url] = page
    return page

##Better
def cache(*arg):
    pass

@cache
def web_lookup(url):
    return urllib.urlopen(url).read()

##Concatenating strings
names = ['raymond', 'rachel', 'matthew', 'roger',
         'betty', 'melissa', 'judith', 'charlie']


s = names[0]
for name in names[1:]:
    s += ','+name
print(s)
##Better
print(','.join(names))

二、Reference

1)github:https://gist.github.com/JeffPaine/6213790
2)youtube:https://www.youtube.com/watch?v=OSGv2VnC0go&t=1253s
3)https://dev.to/dawranliou/never-write-for-loops-again

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,745评论 2 45
  • 今天15:00,你更新了朋友圈,发了一张你的照片,我在10分钟后看到。我很想点赞,又忍住了。还是让我悄无声息地消失...
    曦毒者的低语阅读 1,229评论 0 0
  • 昨天在创意之旅涵予讲课的过程中 他也进入到睡眠时间段 开始没穿纸尿裤 吃了会儿奶告诉我 屁股眼痒痒 掀开被子看了看...
    关关Steven阅读 1,477评论 2 3
  • 蓝色海平面上由波涛形成的白色轨迹,其实每一朵浪花都身不由己。 快艇上的人们也一样。 记泰国游一行的“同路人” 【经...
    两碗米饭阅读 1,837评论 0 0
  • 恋雪·情 天冷了, 天空中, 慢慢飘下片片洁白的小雪花, 伸开手去触摸它 它很淘气 躲闪开了 悄悄的亲下我的脸庞 ...
    恰是你的微柔阅读 1,328评论 0 0

友情链接更多精彩内容