所以,我正在观看Raymond Hettinger的演讲,将代码转换为美丽的,惯用的Python,并且他提出了iter我从未意识到的这种形式.他的例子如下:
代替:
blocks = []
while True:
block = f.read(32)
if block == '':
break
blocks.append(block)
Run Code Online (Sandbox Code Playgroud)
使用:
blocks = []
read_block = partial(f.read, 32)
for block in iter(read_block, ''):
blocks.append(block)
Run Code Online (Sandbox Code Playgroud)
检查完文档后iter,我发现了一个类似的例子:
with open('mydata.txt') as fp:
for line in iter(fp.readline, ''):
process_line(line)
Run Code Online (Sandbox Code Playgroud)
这看起来对我很有用,但我想知道你是否Pythonistas知道这个构造的任何不涉及I/O读取循环的例子?也许在标准库中?
我可以想到非常人为的例子,如下所示:
>>> def f():
... f.count += 1
... return f.count
...
>>> f.count = 0
>>> list(iter(f,20))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, …Run Code Online (Sandbox Code Playgroud) 多处理模块对于python初学者来说非常困惑,特别是那些刚刚从MATLAB迁移并且使用并行计算工具箱变得懒惰的人.我有以下功能需要大约80秒运行,我想通过使用Python的多处理模块来缩短这个时间.
from time import time
xmax = 100000000
start = time()
for x in range(xmax):
y = ((x+5)**2+x-40)
if y <= 0xf+1:
print('Condition met at: ', y, x)
end = time()
tt = end-start #total time
print('Each iteration took: ', tt/xmax)
print('Total time: ', tt)
Run Code Online (Sandbox Code Playgroud)
这按预期输出:
Condition met at: -15 0
Condition met at: -3 1
Condition met at: 11 2
Each iteration took: 8.667453265190124e-07
Total time: 86.67453265190125
Run Code Online (Sandbox Code Playgroud)
由于循环的任何迭代都不依赖于其他循环,我尝试从官方文档中采用此服务器进程来在单独的进程中扫描范围的块.最后我想出了vartec对这个问题的回答,可以准备以下代码.我还根据Darkonaut对当前问题的回答更新了代码.
from time import time
import multiprocessing as …Run Code Online (Sandbox Code Playgroud) python parallel-processing multiprocessing python-3.x python-multiprocessing