>>> for i, value in enumerate(['A', 'B', 'C']): ... print(i, value) ... 0 A 1 B 2 C
iterable
1
有点像java里的iterable
列表生成式
1 2 3 4 5 6 7
列表生成式 [x * x for x in range(1, 11)] [x * x for x in range(1, 11) if x % 2 == 0]
>>> [m + n for m in 'ABC' for n in 'XYZ'] ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
生成器generator yield
1 2 3
列表生成式需要一次性把所有元素计算出来,如果访问时只访问了前几个元素,那么会比较浪费空间
生成器是边迭代边计算值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
列表生成式用[],生成器用() 法一:g = (x * x for x in range(10)) 可以用next(g)去取值,但是常用for in循环去取值
法二:用函数(generator函数) # 斐波拉契数列(Fibonacci) def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' 在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行
from multiprocessing import Process p = Process(target=run_proc, args=('test',)) p.start() p.join() from multiprocessing import Pool p = Pool(4) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all subprocesses done...') p.close() p.join() 进程间通信 Queue、Pipes
from multiprocessing import Process, Queue import os, time, random
# 写数据进程执行的代码: def write(q): print('Process to write: %s' % os.getpid()) for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random())
# 读数据进程执行的代码: def read(q): print('Process to read: %s' % os.getpid()) while True: value = q.get(True) print('Get %s from queue.' % value)
Process to write: 50563 Put A to queue... Process to read: 50564 Get A from queue. Put B to queue... Get B from queue. Put C to queue... Get C from queue.
线程
1 2 3 4 5
import time, threading
t = threading.Thread(target=loop, name='LoopThread') t.start() t.join()
def consumer(): r = '' while True: n = yield r if not n: return print('[CONSUMER] Consuming %s...' % n) r = '200 OK'
def produce(c): c.send(None) n = 0 while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) c.close()
c = consumer() produce(c)
aiohttp
分布式进程
1
from multiprocessing.managers import BaseManager
多进程和多线程java
创建新线程
1 2 3 4 5 6 7 8 9 10
Thread t = new MyThread(); t.start(); // 启动新线程 Thread t = new Thread(new MyRunnable()); t.start(); // 启动新线程
Thread t = new Thread(() -> { System.out.println("start new thread!"); }); t.start(); // 启动新线程
// 多线程 public class Main { public static void main(String[] args) throws Exception { var add = new AddThread(); var dec = new DecThread(); add.start(); dec.start(); add.join(); dec.join(); System.out.println(Counter.count); } }
class Counter { public static final Object lock = new Object(); public static int count = 0; }
class AddThread extends Thread { public void run() { for (int i=0; i<10000; i++) { synchronized(Counter.lock) { Counter.count += 1; } } } }
class DecThread extends Thread { public void run() { for (int i=0; i<10000; i++) { synchronized(Counter.lock) { Counter.count -= 1; } } } }