和其他数据结构,如列表、元组一样,字符串的索引同样从 0 开始,index=0 表示第一个元素(字符),[index:index+2] 则表示第 index 个元素到 index+1 个元素组成的子字符串。
字符串是不可变的(immutable)
字符串格式化
1 2
print('no data available for person with id: {}, name: {}'.format(id, name)) '''最新规范''' print('no data available for person with id: %s, name: %s' % (id, name))'''以往规范,%s 表示字符串型,%d 表示整型'''
json
json.dumps() 这个函数,接受 基本数据类型,然后将其序列化为 string
json.loads() 这个函数,接受一个合法字符串,然后将其反序列化为基本数据类型
条件与循环
条件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
# y = |x| if x < 0: y = -x else: y = x # 场景二 if condition_1: statement_1 elif condition_2: statement_2 ... elif condition_i: statement_i else: statement_n
# 列表 l = [1, 2, 3, 4] for item in l: print(item) 1 2 3 4 # 字典 d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'} for k in d: # 遍历字典的键 print(k) name dob gender for v in d.values(): # 遍历字典的值 print(v) jason 2000-01-01 male for k, v in d.items(): # 遍历字典的键值对 print('key: {}, value: {}'.format(k, v)) key: name, value: jason key: dob, value: 2000-01-01 key: gender, value: male
while
1 2 3 4 5 6 7 8 9 10 11 12
whileTrue: try: text = input('Please enter your questions, enter "q" to exit') if text == 'q': print('Exit system') break ... ... print(response) exceptas err: print('Encountered error: {}'.format(err)) break
classDocument(): WELCOME_STR = 'Welcome! The context for this book is {}.' def__init__(self, title, author, context): print('init function called') self.title = title self.author = author self.__context = context # 类函数 @classmethod defcreate_empty_book(cls, title, author): return cls(title=title, author=author, context='nothing') # 成员函数 defget_context_length(self): returnlen(self.__context) # 静态函数 @staticmethod defget_welcome(context): return Document.WELCOME_STR.format(context) empty_book = Document.create_empty_book('What Every Man Thinks About Apart from Sex', 'Professor Sheridan Simove') print(empty_book.get_context_length()) print(empty_book.get_welcome('indeed nothing')) ########## 输出 ########## init function called 7 Welcome! The context for this book is indeed nothing.
defmy_decorator(func): defwrapper(*args, **kwargs): print('wrapper of decorator') func(*args, **kwargs) return wrapper
- 装饰器可以接受原函数任意类型和数量的参数,除此之外,它还可以接受自己定义的参数。
```python defrepeat(num): defmy_decorator(func): defwrapper(*args, **kwargs): for i inrange(num): print('wrapper of decorator') func(*args, **kwargs) return wrapper return my_decorator @repeat(4) defgreet(message): print(message) greet('hello world') # 输出: wrapper of decorator hello world wrapper of decorator hello world wrapper of decorator hello world wrapper of decorator hello world
classCount: def__init__(self, func): self.func = func self.num_calls = 0 def__call__(self, *args, **kwargs): self.num_calls += 1 print('num of calls is: {}'.format(self.num_calls)) return self.func(*args, **kwargs) @Count defexample(): print("hello world") example() # 输出 num of calls is: 1 hello world example() # 输出 num of calls is: 2 hello world
并发通常应用于 I/O 操作频繁的场景,比如你要从网站上下载多个文件,I/O 操作的时间可能会比 CPU 运行处理的时间长得多。
而并行则更多应用于 CPU heavy 的场景,比如 MapReduce 中的并行计算,为了加快运行速度,一般会用多台机器、多个处理器来完成。
futures实现并行
1 2 3 4 5 6 7 8 9
defdownload_all(sites): with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor: to_do = [] for site in sites: future = executor.submit(download_one, site) to_do.append(future) for future in concurrent.futures.as_completed(to_do): future.result()
函数 ProcessPoolExecutor() 表示创建进程池,使用多个进程并行的执行程序。不过,这里我们通常省略参数 workers,因为系统会自动返回 CPU 的数量作为可以调用的进程数。
总结
1 2 3 4 5 6 7 8
# 伪代码 if io_bound: if io_slow: print('Use Asyncio') else: print('Use multi-threading') elseif cpu_bound: print('Use multi-processing')
GIL
Global Interpreter Lock,即全局解释器锁
python引进GIL的原因
一是设计者为了规避类似于内存管理这样的复杂的竞争风险问题(race condition);
二是因为 CPython 大量使用 C 语言库,但大部分 C 语言库都不是原生线程安全的(线程安全会降低性能和增加复杂度)
工作机制
check interval
CPython 中还有另一个机制,叫做 check_interval,意思是 CPython 解释器会去轮询检查线程 GIL 的锁住情况。每隔一段时间,Python 解释器就会强制当前线程去释放 GIL,这样别的线程才能有执行的机会。
例子2: assert1 == 2, 'assertion is wrong' 相当于 if__debug__: ifnot expression1: raise AssertionError(expression2) 例子3(促销价格大于0元): defapply_discount(price, discount): updated_price = price * (1 - discount) assert0 <= updated_price <= price, 'price should be greater or equal to 0 and less or equal to original price' return updated_price
不要在使用 assert 时加入括号,否则无论表达式对与错,assert 检查永远不会 fail
with
在 Python 中,解决资源泄露的方式是上下文管理器(context manager)。上下文管理器,能够帮助你自动分配并且释放资源,其中最典型的应用便是 with 语句
classFileManager: def__init__(self, name, mode): print('calling __init__ method') self.name = name self.mode = mode self.file = None def__enter__(self): print('calling __enter__ method') self.file = open(self.name, self.mode) return self.file def__exit__(self, exc_type, exc_val, exc_tb): print('calling __exit__ method') if self.file: self.file.close() # 使用 with FileManager('test.txt', 'w') as f: print('ready to write to file') f.write('hello world')
基于生成器的上下文管理器
使用装饰器 contextlib.contextmanager,来定义自己所需的基于生成器的上下文管理器,用以支持 with 语句
1 2 3 4 5 6 7 8 9 10 11 12
from contextlib import contextmanager @contextmanager deffile_manager(name, mode): try: f = open(name, mode) yield f finally: f.close() with file_manager('test.txt', 'w') as f: f.write('hello world')
性能调试
cProfile
用法 tips
引用规范 from your_file import function_name, class_name
Keep in mind that, in Ignite, the concepts of a SQL table and a key-value cache are two equivalent representations of the same (internal) data structure. You can access your data using either the key-value API or SQL statements, or both.
A cache is a collection of key-value pairs that can be accessed through the key-value API. A SQL table in Ignite corresponds to the notion of tables in traditional RDBMSs with some additional constraints; for example, each SQL table must have a primary key.
A table with a primary key can be presented as a key-value cache, in which the primary key column serves as the key, and the rest of the table columns represent the fields of the object (the value).