开发者

Create a list with boolean values which represent results of a predicate when applied to a list

开发者 https://www.devze.com 2023-03-11 07:56 出处:网络
I am trying to figure out if there is a way to get a logical list through comparison in Python 3. Basically what I want to input is this

I am trying to figure out if there is a way to get a logical list through comparison in Python 3. Basically what I want to input is this

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]
xlist = 4 <= x
开发者_StackOverflow社区

and what I am looking to output is a list that would look like this

xlist = [False, False, False, True, True, True, True, True, True]

Is there anyway to do this simply without using list comprehension like

xlist = [4 <= i for i in x]

Is there anything that would be more efficient with larger lists?


There is really nothing wrong with a list comprehension. This is exactly the sort of thing list comprehensions were designed for.

If you're using NumPy (or SciPy), the syntax you're looking for actually does work:

from numpy import array

...

x = array([1,2,3,4,5,6,7,8,9])
xlist = 4<=x

But if you don't already have a good reason to use NumPy, it's not worth bringing it in just for that syntax. In any case, come to think of it I'm not sure if NumPy works in Python 3 yet.


One thing to consider would be whether you need the intermediate list or not. If not use a generator expression instead. For instance all(i <= 4 for i in x) would be substantially faster and would use less memory than all([i <= 4 for i in x]).


The map approach is likely to be the faster but, please, profile them if you really want to know.

Also consider the array module.

In [2]: %timeit map(lambda i: 4<=i, xrange(1,100))
100000 loops, best of 3: 15.9 us per loop

In [7]: %timeit list(4<=i for i in range(1,100))
100000 loops, best of 3: 10.3 us per loop

In [8]: %timeit list(4<=i for i in range(1,1000))
10000 loops, best of 3: 80.6 us per loop

In [10]: %timeit map(lambda i: 4<=i, xrange(1,1000))
10000 loops, best of 3: 155 us per loop


You also can use the following:

print map(lambda i: 4<=i, xrange(1,10))


For large lists, this:

>>> (4<=i for i in range(1,10))
<generator object <genexpr> at 0xb75beedc>
>>> list(_)
[False, False, False, True, True, True, True, True, True]
# The list(_) is just to show what is inside the generator...

is better than:

>>> [4<=i for i in range(1,10)]
[False, False, False, True, True, True, True, True, True]

As I understand it, there is much less of a speed advantage to a list comprehension vs generator comprehension in Python 3 vs Python 2. This syntax works with both and the advantage for large list is the same: the list elements are all generated at once vs a generator is generated as needed.


I think you are already doing it the right way.

0

精彩评论

暂无评论...
验证码 换一张
取 消