使用这个 setitem 函数来克服列表理解限制会不会很不Pythonic?
>>> a=range(5)
>>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects
[0, 2, 4]
>>> a
[0, 1, 2, 3, 4]
>>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment
SyntaxError: invalid syntax
>>> def setitem(listtochange,n,value): ## function to overcome limitation
listtochange[n]=value
return value
>>> [setitem(a,i,'x') for i in range(0,len(a),2)] ## proving the function
['x', 'x', 'x']
>>> a
['x', 1, 'x', 3, 'x'] # We did assignment anyway
>>> a=range(5)
>>> [a[i] for i in range(0,len(a),2)] ## list comprehension for side effects
[0, 2, 4]
>>> a
[0, 1, 2, 3, 4]
>>> [a[i]=3 for i in range(0,len(a),2)] ## try to do assignment
SyntaxError: invalid syntax
>>> def setitem(listtochange,n,value): ## function to overcome limitation
listtochange[n]=value
return value
>>> [setitem(a,i,'x') for i in range(0,len(a),2)] ## proving the function
['x', 'x', 'x']
>>> a
['x', 1, 'x', 3, 'x'] # We did assignment anyway
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不要使用列表推导式来执行副作用——这不是Pythonic。使用显式循环代替:
除了列表推导式中令人惊讶和意外的副作用之外,您正在构建一个您从未使用过的结果列表,这在这里是浪费且完全不必要的。
Don't use list comprehensions to perform side-effects - that is not Pythonic. Use an explicit loop instead:
Apart the side-effects in list comprehensions being surprising and unexpected, you are constructing a result list that you never use which is wasteful and completely unnecessary here.
是的。我建议使用
它。
编辑:
Python 2.6 的微基准:
Python 3.1:
Yes. And I recommend using
instead.
Edit:
Microbenchmarks for Python 2.6:
Python 3.1:
您还可以使用
list.__setitem__
或者,如果您想避免构建中间列表:
但是列表推导式中的赋值确实是unpythonic。
You can also use
list.__setitem__
Or if you want to avoid the contruction of an intermediate list:
But assignment in list comprehensions is indeed unpythonic.
对于我提到的时间安排(另请参阅通过递归公式改进纯Python素数筛)
from time import Clock
Length 函数和所有带有 setitem 的函数都不是令人满意的替代方案,但这里的计时可以证明这一点。
具有len功能的rwh筛子
长度 78498,257.80008353 ms
rwh 筛,any 有副作用
长度 78498,829.977273648 毫秒
For my timing mentioned (see also the Improving pure Python prime sieve by recurrence formula)
from time import clock
Length function and all with setitem are not satisfactory alternatives, but the timings are here to demonstrate it.
rwh sieve with len function
Length 78498, 257.80008353 ms
rwh sieve with any with side effects
Length 78498, 829.977273648 ms