Python
contextlib
contextlib
利用__enter__
和__exit__
这两个方法实现上下文管理,就可以用with
语句。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| class Query(object):
def __init__(self, name):
self.name = name
def __enter__(self):
print('Begin')
return self
def __exit__(self, exc_type, exc_value, traceback):
if exc_type:
print('Error')
else:
print('End')
def query(self):
print('Query info about %s...' % self.name)
|
1
2
| with Query('Bob') as q:
q.query()
|
Python的标准库contextlib
提供了更简单的写法。
@contextmanager
这个decorator接受一个generator,yield
语句生成的变量就是with ... as var
中的变量。
with
语句首先执行yield
之前的语句,yield
调用会执行with
语句内部的所有语句,最后执行yield
之后的语句。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| from contextlib import contextmanager
class Query(object):
def __init__(self, name):
self.name = name
def query(self):
print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
yield q
print('End')
|
1
2
| with create_query('Bob') as q:
q.query()
|
1
2
3
4
5
6
7
8
| import contextlib
import time
@contextlib.contextmanager
def elapsed_timer(message):
start_time = time.time()
yield
LOGGER.info(message.format(time.time() - start_time))
|
getattr
getattr
如果属性查找(attribute lookup)在实例以及对应的类中(通过__dict__)失败, 那么会调用到类的__getattr__函数, 如果没有定义这个函数,那么抛出AttributeError异常。
1
2
3
4
5
6
7
8
9
| class StubLogger(object):
def __getattr__(self, name):
return self.log_print
def log_print(self, msg, *args):
print(msg % args)
LOGGER = StubLogger()
LOGGER.info("Hello %s!", "world")
|
文件
读文件
读文件
1
2
3
| with open('filename') as file:
for line in file:
do_things(line)
|
写文件
1
2
| with open('filename') as file:
file.write()
|
路径拼接
1
| os.path.join(path1, path2)
|
String Split and Join
String Split and Join
In Python, a string can be split on a delimiter.
1
| list = string.split(" ")
|
Joining a string is simple:
1
| string = "-".join(list)
|
字典遍历
python字典遍历的几种方法
1
2
3
4
| for key in dict:
for key in dict.keys():
for value in dict.values():
for key, value in dict.items():
|
排列
python 全排列combinations和permutations函数
1
2
3
4
| import itertools
s = [1, 2, 3]
print(list(itertools.combinations('abc', 2))) # [('a', 'b'), ('a', 'c'), ('b', 'c')]
print(list(itertools.permutations(s, 3))) # [(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
|
序列化
1
2
| pickle.dump(variable, open('path.pkl', 'wb'))
variable = pickle.load(open('path.pkl', 'rb'))
|
Pandas
遍历DataFrame
1
2
| for index, row in df.iterrows():
row["column_name"]
|
行选择
列选择
1
| df.loc[:, ["column1", "column2"]]
|
值选择
1
| df.loc[df["column"] == value]
|
loc和iloc的区别
https://stackoverflow.com/questions/31593201/how-are-iloc-and-loc-different
- loc gets rows (or columns) with particular labels from the index.
- iloc gets rows (or columns) at particular positions in the index (so it only takes integers).
取值
1
| df.reset_index().at[0, "ndcg_at_10"]
|
读取csv
1
| action_data = pd.read_csv(data_path + 'Clothing_Shoes_and_Jewelry.csv', header=None, names=["user_id", "sku_id", "rating", "timestamp"])
|
C++
argc & argv
Regarding main(int argc, char *argv[])
$ mysort 2 8 9 1 4 5
Argument Count, argc = 7
Argument Vector, argv[] = { “mysort”, “2”, “8”, “9”, “1”, “4”, “5” };
IDE
IDEA
- ctrl
- ctrl alt <-
- ctrl f12
- ctrl shift f
- shift shift
VSCode
- ctrl
- alt <-
- ctrl shift o
- shift alt f