什么时候应该使用生成器表达式?什么时候应该在Python中使用列表推导?
# Generator expression
(x*2 for x in range(256))
# List comprehension
[x*2 for x in range(256)]
Run Code Online (Sandbox Code Playgroud) 我开始学习Python,我遇到了生成器函数,那些在它们中有yield语句的函数.我想知道这些函数真正擅长解决哪些类型的问题.
从标题来看,是的,有区别.现在适用于我的场景:让我们考虑一个类Dummy:
class Dummy:
def __init__(self):
self.attached = []
def attach_item(self, item):
self.attached.append(item)
Run Code Online (Sandbox Code Playgroud)
如果我用这个:
D = Dummy()
items = [1, 2, 3, 4]
for item in items:
D.attach_item(item)
Run Code Online (Sandbox Code Playgroud)
我确实得到了D.attached = [1, 2, 3, 4].但是如果我将函数映射attach_item到items,则D.attached保持为空.
map(D.attach_item, items)
Run Code Online (Sandbox Code Playgroud)
它在做什么?
怎么了?有人可以解释一下这里发生了什么,我在紧密循环中改变了:
## j=i
## while j < ls - 1 and len(wordlist[j]) > lc: j+=1
j = next(j for j in range(i,ls) if len(wordlist[j]) <= lc)
Run Code Online (Sandbox Code Playgroud)
评论的版本运行整个程序:625毫秒,下一个生成器版本在2.125秒的时间内运行整个程序.
有什么理由可以说这个更加pythonic的版本会导致性能上的这种灾难?
编辑:也许它是由使用psyco模块引起的?当然至少没有psyco的Python 2.7的运行时间对于下一个版本来说是2.141,意味着与使用psyco的Python 2.6几乎相同.
删除*.pyc文件后,我得到的代码没有减速.然后,当我从库模块中删除了psyco的导入时,我还得到了2.6时序,没有psyco使用,非psyco版本和psyco版本的结果(现在库例程也慢了,它的时间也相关:)
不是psyco:
Psyco是:
在带有2GB RAM的WindowsXP AMD Sempron 3100+系统中运行.使用两个全局变量计算循环和调用:
j=i
callcount += 1
while j < ls - 1 and len(wordlist[j]) > lc:
j+=1
loopcount += 1
Run Code Online (Sandbox Code Playgroud)
使用psyco进行测试输入的结果:
Finished in 625 ms
Loopcount: 78317 …Run Code Online (Sandbox Code Playgroud) 在低长度迭代次数的限制中考虑以下操作,
d = (3, slice(None, None, None), slice(None, None, None))
In [215]: %timeit any([type(i) == slice for i in d])
1000000 loops, best of 3: 695 ns per loop
In [214]: %timeit any(type(i) == slice for i in d)
1000000 loops, best of 3: 929 ns per loop
Run Code Online (Sandbox Code Playgroud)
设置为a list比使用生成器表达式快25%?
为什么这样设置为a list是一个额外的操作.
注意:在两次运行中,我都获得了警告:The slowest run took 6.42 times longer than the fastest. This could mean that an intermediate result is being cachedI
在该特定测试中,list()结构更快,直到 …
就像是
sentence.replace(*, "newword")
(这不起作用,顺便说一句)
让我们说吧
sentence = "hello world"
return sentence.replace(*, "newworld")
应该返回"newword newword"
python ×6
generator ×3
optimization ×2
python-3.x ×2
caching ×1
function ×1
iteration ×1
list ×1
methods ×1
performance ×1
python-2.7 ×1
string ×1
while-loop ×1