List comprehension complement in python

I am wondering if there is no way to compute the complement of list comprehension in Python. Sort of:

evens = [i in range(10) if i % 2 == 0]
odds  = [i in range(10) if i % 2 != 0]

Is there a way to get both evens and odds in one call? For a very large list or more expensive if statement, I think it will save a lot of time.

+4
source share
4 answers

I believe this question was asked before, but I have not found the link at this time.

If you are trying to get more than one predicate, and you only want to iterate over the original generator, you will have to use a simple loop for.

evens = []
odds = []

for i in xrange(10):
   if i % 2 == 0: evens.append(i)
   else: odds.append(i)

@dawg, , .

for i in xrange(10):
   (evens,odds)[i%2].append(i)
+4

itertools.groupby - , .

In [1]: import itertools as it

In [2]: key = lambda i: i%2 == 0

In [3]: l = list(range(10))

In [4]: l.sort(key=key)

In [5]: [list(i[1]) for i in it.groupby(l, key=key)]
Out[5]: [[1, 3, 5, 7, 9], [0, 2, 4, 6, 8]]
+1

:

evens = [i in range(10) if i % 2 == 0]
odds  = [i in range(10) if i not in evens]

:

evens = [i in range(10) if i % 2 == 0]
evens_set = set(evens)
odds = [i in range(10) if i not in evens_set]

set , not in O(1) O(n)

0

, True, False , .

range_10 = range(10)
odds = range_10[1::2]
evens = range_10[::2]

. (, ). , (10) , .

slicing, , , .

0

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


All Articles