This issue tracker has been migrated to GitHub ,
and is currently read-only.
For more information,
see the GitHub FAQs in the Python's Developer Guide.
Created on 2014年09月19日 20:30 by cool-RR, last changed 2022年04月11日 14:58 by admin. This issue is now closed.
| Messages (5) | |||
|---|---|---|---|
| msg227117 - (view) | Author: Ram Rachum (cool-RR) * | Date: 2014年09月19日 20:30 | |
Can't this code: class Sequence(Sized, Iterable, Container): # ... def __contains__(self, value): for v in self: if v == value: return True return False Be shortened into this: class Sequence(Sized, Iterable, Container): # ... def __contains__(self, value): return any(item == value for value in self) Which can even fit on one line with a lambda: class Sequence(Sized, Iterable, Container): # ... __contains__ = lambda self: any(item == value for value in self) |
|||
| msg227120 - (view) | Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) | Date: 2014年09月19日 20:57 | |
This is slower.
>>> import timeit
>>> class A(list):
... def __contains__(self, value):
... for v in self:
... if v == value:
... return True
... return False
...
>>> timeit.timeit('500 in x', setup='from __main__ import A; x = A(range(1000))', number=10000)
1.1222619999971357
>>> class B(list):
... def __contains__(self, value):
... return any(v == value for v in self)
...
>>> timeit.timeit('500 in x', setup='from __main__ import B; x = B(range(1000))', number=10000)
2.05952100000286
|
|||
| msg227121 - (view) | Author: Ram Rachum (cool-RR) * | Date: 2014年09月19日 20:59 | |
Oh. I wonder why `any` is slow like that, you'd figure it's be optimized. |
|||
| msg227124 - (view) | Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) | Date: 2014年09月19日 21:15 | |
Because in first case there is one iterator, iter(self), and in second case there are two iterators: iter(self) and iter((v == value for v in self)). |
|||
| msg227125 - (view) | Author: Ram Rachum (cool-RR) * | Date: 2014年09月19日 21:21 | |
Thanks for the clarification. Oh well, sad to see the more verbose code win, but I guess that's life. I tried on PyPy but the difference was even more pronounced, 0.008922450399566156 for the long version and 0.042124665810088044 for the short version. |
|||
| History | |||
|---|---|---|---|
| Date | User | Action | Args |
| 2022年04月11日 14:58:08 | admin | set | github: 66636 |
| 2014年09月19日 21:35:58 | benjamin.peterson | set | status: open -> closed resolution: rejected |
| 2014年09月19日 21:21:03 | cool-RR | set | messages: + msg227125 |
| 2014年09月19日 21:15:54 | serhiy.storchaka | set | messages: + msg227124 |
| 2014年09月19日 20:59:35 | cool-RR | set | messages: + msg227121 |
| 2014年09月19日 20:57:15 | serhiy.storchaka | set | nosy:
+ serhiy.storchaka messages: + msg227120 |
| 2014年09月19日 20:30:20 | cool-RR | create | |