"and" and "or" on every item in a list
Dustan
DustanGroups at gmail.com
Mon Oct 29 22:00:12 EDT 2007
More information about the Python-list mailing list
Mon Oct 29 22:00:12 EDT 2007
- Previous message (by thread): "and" and "or" on every item in a list
- Next message (by thread): interesting threading result..
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On Oct 29, 5:57 pm, GHZ <geraint.willi... at gmail.com> wrote: > Is this the best way to test every item in a list? No. The biggest problem is, obviously, you don't take advantage of builtins any() and all(), or write corresponding short-circuiting versions for python versions before 2.5. The second problem is you build an entire list that gets disposed of just as quickly. The third problem is you use lambda, which makes your call to map() time inefficient as well as space inefficient. Both of these problems can be fixed by using generator expressions. > def alltrue(f,l): > return reduce(bool.__and__,map(f,l)) > > def onetrue(f,l): > return reduce(bool.__or__,map(f,l)) > > > > >>> alltrue(lambda x:x>1,[1,2,3]) > False >>> all(x>1 for x in [1,2,3]) False > >>> alltrue(lambda x:x>=1,[1,2,3]) > True >>> all(x>=1 for x in [1,2,3]) True > Thanks HTH
- Previous message (by thread): "and" and "or" on every item in a list
- Next message (by thread): interesting threading result..
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list