python - Split list by criterion -


this question has answer here:

let's have list of numbers , want split list 2 sublists: 1 odd numbers , 1 evens.

evens, odds = [], [] e in numbers:     if e % 2 == 0:         evens.append(e)     else:         odds.append(e) 

i wonder if there one-liner problem while keeping same order of complexity.

i tried using itertools.groupby list needs ordered first i'd achieving o(2n) rather o(n):

def is_even(n):     return n % 2 == 0  lst = sorted(lst, key=is_even) grouper = itertools.groupby(lst, key=is_even) lst1, lst2 = [list(v) k, v in grouper] 

how using ternary operator prior append:

evens, odds = [], [] e in numbers:     (odds if e % 2 else evens).append(e) 

of course inside list comprehension, it's not pythonic use comprehension it's side-effects because create potentially large unwanted list of none values. instead use itertools consume recipe if want take route.


Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -