Return true or false in python list comprehension

The goal is to write a function that takes in the list, and whether the numbers in the list return, even leading to True or False. Ex. [1, 2, 3, 4] ---> [False, True, False, True]

I wrote this piece of code:

def even_or_odd(t_f_list):
   return = [ x for x in t_f_list if x % 2 == 0]

I know that this code will return [2, 4]. How can I do this to return true and false instead, as in the above example?

+4
source share
3 answers

Instead of filtering by predicate, you should match it:

def even_or_odd(t_f_list):
   return [ x % 2 == 0 for x in t_f_list]
+13
source

You can use lambda instead:

l = [1,2,3,4]
map(lambda x: x%2 == 0, l)
+3
source

& , , %:

t_f_list = [1,2,3,4]
res = [ not x&1 for x in t_f_list]
print(res)
[False, True, False, True]

Timing

In [72]: %timeit [not x&1 for x in t_f_list]
1000000 loops, best of 3: 795 ns per loop

In [73]: %timeit [ x % 2 == 0 for x in t_f_list]
1000000 loops, best of 3: 908 ns per loop

In [74]: %timeit list(map(lambda x: x%2 == 0, t_f_list))
1000000 loops, best of 3: 1.87 us per loop

: list map list, python 3.x

+1

Source: https://habr.com/ru/post/1627265/


All Articles