Python特有简写
快速生成随机数组
random_array = [random.randint(0,100) for i in range(10)]
# 输出
[77, 76, 31, 0, 18, 17, 89, 85, 31, 13]
等价于
random_array = []
for i in range(10):
random_array.append(random.randint(0,100))
其中i
为临时变量,可使用_
替代
无参数lambda使用
符号:
之前无内容
f = lambda: random.randint(0,100)
Python多线程
threading
使用threading,相当于Java中的Runable
或Callable
import threading
import time
import random
def print_task():
delay = random.randint(1, 5)
time.sleep(delay)
print(threading.current_thread().name, "delay", delay, "seconds")
if __name__ == '__main__':
print('当前运行的是主进程', threading.current_thread().name)
t = threading.Thread(target=print_task, name='t-1')
# 启动线程
t.start()
t.join()
线程池
推荐使用ThreadPoolExecutor,并推荐命名线程
from concurrent.futures import ThreadPoolExecutor, wait
import time
import random
import threading
def print_task():
delay = random.randint(1, 5)
time.sleep(delay)
print(threading.current_thread().name, "delay", delay, "seconds")
executor = ThreadPoolExecutor(max_workers=5, thread_name_prefix="print-task")
all_future = [executor.submit(print_task) for _ in range(10)]
wait(all_future)
总结
- python菜鸟一点一点积累