前些日子重读《Python Cookbook》,对书中的一些小技巧爱不释手,今天又看到这个PyTricks,决定将自己喜欢/常用的一些技巧摘录下来,加入到日常tricks里。

#exec exec("print('Hello ' + s)", {'s': 'World'})

exec can be used to execute Python code during runtime.
variables can be handed over as a dict(相当于环境)

#calculator

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
'''使用字典搜索来实现 if..else 逻辑'''
import operator
ops = {
    "+": operator.add,
    "-": operator.sub,
    "/": operator.truediv,
    "*": operator.mul
}

x = input("Enter an operator [OPTIONS: +, -, *, /]: ")
y = int(input("Enter number: "))
z = int(input("Enter number: "))

print (ops[x](y, z))

swicth在python中

1
2
3
4
5
def f(x):
    return {
        'a': 1,
        'b': 2,
    }.get(x, 9)

#conditional function call

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
'''calling different functions with same arguments based on condition'''

def product(a, b):
    return a * b

def subtract(a, b):
    return a - b

b = True
print((product if b else subtract)(1, 1))

#dictionary get

1
2
3
"""returning None or default value, when key is not in dict"""
d = {'a': 1, 'b': 2}
print(d.get('c', 3))

#dict sort by value

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
""" Sort a dictionary by its values with the built-in sorted() function and a 'key' argument. """
 
d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1}
print(sorted(d.items(), key=lambda x: x[1]))

""" Sort using operator.itemgetter as the sort key instead of a lambda"""

from operator import itemgetter
print(sorted(d.items(), key=itemgetter(1)))

"""Sort dict keys by value"""

print(sorted(d, key=d.get))

#operator document

让你更方便地使用函数式风格

#tree

1
2
3
4
5
6
7
from collections import defaultdict

tree = lambda: defaultdict(tree)

users = tree()
users['harold']['username'] = 'chopper'
users['matt']['password'] = 'hunter2'

#正则表达式 ##灵活切割字符串

1
2
3
4
line = 'asdf fjdk; afed, fjek,asdf, foo'
import re
re.split(r'[;,\s]\s*', line)
#['asdf', 'fjdk', 'afed', 'fjek', 'asdf', 'foo']

##匹配和搜索

1
2
3
4
5
6
7
8
9
import re
text = 'Today is 11/27/2012. PyCon starts 3/13/2013.'
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
match1 = datepat.match(text)
#match1.groups() =>'NoneType' object has no attribute 'groups'
match2 = datepat.search(text)
#match.groups() => ('11', '27', '2012')
match3 = datepat.findall(text)
#=>[('11', '27', '2012'), ('3', '13', '2013')]

##搜索和替换

1
2
3
4
import re
datepat = re.compile(r'(\d+)/(\d+)/(\d+)')
datepat.sub(r'\3-\1-\2', text)
#更复杂的替换,sub的第一个参数可以是callback,默认传入match对象

#时间和日期 ##字符串转换为日期

1
2
3
from datetime import datetime
text = '2012-09-20'
y = datetime.strptime(text, '%Y-%m-%d')

#文件IO ##读写文本文件

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# Read the entire file as a single string
with open('somefile.txt', 'rt') as f:
    data = f.read()

# Iterate over the lines of the file
with open('somefile.txt', 'rt') as f:
    for line in f:
        # process line
        ...
########
# Write chunks of text data
with open('somefile.txt', 'wt') as f:
    f.write(text1)
    f.write(text2)
    ...

# Redirected print statement
with open('somefile.txt', 'wt') as f:
    print(line1, file=f)
    print(line2, file=f)
    ...

##读写json

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import json

data = {
    'name' : 'ACME',
    'shares' : 100,
    'price' : 542.23
}

json_str = json.dumps(data)
data = json.loads(json_str)

##读写csv

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
import csv
with open('stocks.csv') as f:
    f_csv = csv.DictReader(f)
    for row in f_csv:
        # process row
        #可以使用列名去访问每一行的数据。如,row['Symbol']
        
#写入
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
         ('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
         ('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
       ]

with open('stocks.csv','w') as f:
    f_csv = csv.writer(f)
    f_csv.writerow(headers)
    f_csv.writerows(rows)
#如果你写入的每一行都是dict,只需要改变writer对象:f_csv = csv.DictWriter(f, headers)    

#可迭代对象 ##循环中获取下标

1
2
for index, value in enumerate(ints):
    print index, value

#元编程 ##装饰器 wait

##自省 检测一个对象是否包含某个属性:if hasattr(obj, 'attr_name')

#参考