Is there a way to âforkâ a list in two based on a condition [duplicate]
![Creative The name of the picture](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgO9GURib1T8z7lCwjOGLQaGtrueEthgQ8LO42ZX8cOfTqDK4jvDDpKkLFwf2J49kYCMNW7d4ABih_XCb_2UXdq5fPJDkoyg7-8g_YfRUot-XnaXkNYycsNp7lA5_TW9td0FFpLQ2APzKcZ/s1600/1.jpg)
![Creative The name of the picture](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhYQ0N5W1qAOxLP7t7iOM6O6AzbZnkXUy16s7P_CWfOb5UbTQY_aDsc727chyphenhyphen5W4IppVNernMMQeaUFTB_rFzAd95_CDt-tnwN-nBx6JyUp2duGjPaL5-VgNO41AVsA_vu30EJcipdDG409/s400/Clash+Royale+CLAN+TAG%2523URR8PPP.png)
up vote
13
down vote
favorite
This question already has an answer here:
Python: split a list based on a condition?
26 answers
I have seen a pattern repeated a couple times in my team's code, it looks like this
numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]
I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)
So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.
Is there something around python's standard library that achieves this?
python list
marked as duplicate by Aran-Fey
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Aug 8 at 11:16
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
add a comment |Â
up vote
13
down vote
favorite
This question already has an answer here:
Python: split a list based on a condition?
26 answers
I have seen a pattern repeated a couple times in my team's code, it looks like this
numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]
I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)
So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.
Is there something around python's standard library that achieves this?
python list
marked as duplicate by Aran-Fey
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Aug 8 at 11:16
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
10
Normally this is called a "partition", there's a recipe initertools
for it.
â jonrsharpe
Aug 8 at 9:09
add a comment |Â
up vote
13
down vote
favorite
up vote
13
down vote
favorite
This question already has an answer here:
Python: split a list based on a condition?
26 answers
I have seen a pattern repeated a couple times in my team's code, it looks like this
numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]
I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)
So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.
Is there something around python's standard library that achieves this?
python list
This question already has an answer here:
Python: split a list based on a condition?
26 answers
I have seen a pattern repeated a couple times in my team's code, it looks like this
numbers = [1, 2, 3, 4]
even_numbers = [n for n in numbers if n % 2 == 0]
odd_numbers = [n for n in numbers if n % 2 != 0]
I was wondering if there is a function somewhere (I have looked around but haven't been able to find it) that would do something like this
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = fork(numbers, lambda x: x % 2 == 0)
So, this function I am looking for, would receive an iterable and a function, and return two lists, one would be the values that match a provided condition, and the other would be the ones that didn't.
Is there something around python's standard library that achieves this?
This question already has an answer here:
Python: split a list based on a condition?
26 answers
python list
python list
edited Aug 8 at 9:10
![](https://i.stack.imgur.com/feZwC.jpg?s=32&g=1)
![](https://i.stack.imgur.com/feZwC.jpg?s=32&g=1)
jonrsharpe
74.8k1089189
74.8k1089189
asked Aug 8 at 9:08
Jose Enrique Narvaez
744
744
marked as duplicate by Aran-Fey
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Aug 8 at 11:16
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
marked as duplicate by Aran-Fey
StackExchange.ready(function()
if (StackExchange.options.isMobile) return;
$('.dupe-hammer-message-hover:not(.hover-bound)').each(function()
var $hover = $(this).addClass('hover-bound'),
$msg = $hover.siblings('.dupe-hammer-message');
$hover.hover(
function()
$hover.showInfoMessage('',
messageElement: $msg.clone().show(),
transient: false,
position: my: 'bottom left', at: 'top center', offsetTop: -7 ,
dismissable: false,
relativeToBody: true
);
,
function()
StackExchange.helpers.removeMessages();
);
);
);
Aug 8 at 11:16
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
10
Normally this is called a "partition", there's a recipe initertools
for it.
â jonrsharpe
Aug 8 at 9:09
add a comment |Â
10
Normally this is called a "partition", there's a recipe initertools
for it.
â jonrsharpe
Aug 8 at 9:09
10
10
Normally this is called a "partition", there's a recipe in
itertools
for it.â jonrsharpe
Aug 8 at 9:09
Normally this is called a "partition", there's a recipe in
itertools
for it.â jonrsharpe
Aug 8 at 9:09
add a comment |Â
6 Answers
6
active
oldest
votes
up vote
11
down vote
accepted
I usually call this sift
, but partition
is fine too.
Another, itertools-less implementation might be
def sift(iterable, predicate):
t =
f =
for value in iterable:
(t if predicate(value) else f).append(value)
return (t, f)
even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):
def sift2(iterable, predicate):
t =
f =
ta = t.append
fa = f.append
for value in iterable:
(ta if predicate(value) else fa)(value)
return (t, f)
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
usingtimeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items.%timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs%timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function call
â roganjosh
Aug 8 at 9:56
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
1
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
add a comment |Â
up vote
3
down vote
You can use the following function:
from itertools import filterfalse, tee
def fork(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))
Source: itertools
add a comment |Â
up vote
2
down vote
I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:
def myFunc(iterable, func):
first = [i for i in iterable if func(i)]
second = [i for i in iterable if not func(i)]
return first,second
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)
print(even_numbers) # [2, 4]
print(odd_numbers) # [1, 3]
add a comment |Â
up vote
2
down vote
Full code following @jonrsharpe suggestion.
import itertools
def fork(iterable):
"Returns list of even, odd elements of a list"
t1, t2 = itertools.tee(iterable)
pred = lambda i: i % 2 == 0
return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))
odd, even = fork([1,2,3,4,5])
print(odd)
print(even)
Alternative numpy version which might be faster for big arrays
import numpy as np
def fork(iterable):
"Returns array of even, odd elements of an array"
iterable_array = np.asarray(iterable)
mask = (iterable_array % 2 == 0)
return iterable_array[~mask], iterable_array[mask]
add a comment |Â
up vote
2
down vote
The simplest possible implementation would be probably
def partition(xs, cond):
res = ,
for x in xs:
res[not cond(x)].append(x)
return res
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
add a comment |Â
up vote
0
down vote
You can create your own function:
l = [1, 2, 3, 4]
def fork(l,key):
return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
print(even_numbers)
print(odd_numbers)
Output:
[2, 4]
[1, 3]
add a comment |Â
6 Answers
6
active
oldest
votes
6 Answers
6
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
11
down vote
accepted
I usually call this sift
, but partition
is fine too.
Another, itertools-less implementation might be
def sift(iterable, predicate):
t =
f =
for value in iterable:
(t if predicate(value) else f).append(value)
return (t, f)
even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):
def sift2(iterable, predicate):
t =
f =
ta = t.append
fa = f.append
for value in iterable:
(ta if predicate(value) else fa)(value)
return (t, f)
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
usingtimeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items.%timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs%timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function call
â roganjosh
Aug 8 at 9:56
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
1
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
add a comment |Â
up vote
11
down vote
accepted
I usually call this sift
, but partition
is fine too.
Another, itertools-less implementation might be
def sift(iterable, predicate):
t =
f =
for value in iterable:
(t if predicate(value) else f).append(value)
return (t, f)
even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):
def sift2(iterable, predicate):
t =
f =
ta = t.append
fa = f.append
for value in iterable:
(ta if predicate(value) else fa)(value)
return (t, f)
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
usingtimeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items.%timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs%timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function call
â roganjosh
Aug 8 at 9:56
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
1
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
add a comment |Â
up vote
11
down vote
accepted
up vote
11
down vote
accepted
I usually call this sift
, but partition
is fine too.
Another, itertools-less implementation might be
def sift(iterable, predicate):
t =
f =
for value in iterable:
(t if predicate(value) else f).append(value)
return (t, f)
even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):
def sift2(iterable, predicate):
t =
f =
ta = t.append
fa = f.append
for value in iterable:
(ta if predicate(value) else fa)(value)
return (t, f)
I usually call this sift
, but partition
is fine too.
Another, itertools-less implementation might be
def sift(iterable, predicate):
t =
f =
for value in iterable:
(t if predicate(value) else f).append(value)
return (t, f)
even, odd = sift([1, 2, 3, 4, 5], lambda x: x % 2 == 0)
EDIT: for a slightly more complex implementation that is about 30% faster (on my Python installation anyway):
def sift2(iterable, predicate):
t =
f =
ta = t.append
fa = f.append
for value in iterable:
(ta if predicate(value) else fa)(value)
return (t, f)
edited Aug 8 at 10:04
answered Aug 8 at 9:23
![](https://i.stack.imgur.com/vVhK5.jpg?s=32&g=1)
![](https://i.stack.imgur.com/vVhK5.jpg?s=32&g=1)
AKX
37.1k34964
37.1k34964
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
usingtimeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items.%timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs%timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function call
â roganjosh
Aug 8 at 9:56
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
1
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
add a comment |Â
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
usingtimeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items.%timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs%timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function call
â roganjosh
Aug 8 at 9:56
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
1
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
I really like this implementation, I will mark it as the answer since it does not use itertools and iterates only once.
â Jose Enrique Narvaez
Aug 8 at 9:25
using
timeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function callâ roganjosh
Aug 8 at 9:56
using
timeit
suggests this takes quite a bit longer than the original approach for a list of 1000 items. %timeit two_lists(lst) 186 µs ± 526 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
vs %timeit using_sift(lst) 290 µs ± 360 ns per loop (mean ± std. dev. of 7 runs, 1000 loops each)
though it does have an additional function callâ roganjosh
Aug 8 at 9:56
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@roganjosh Yeah, that's probably the function call overhead. Can't do much about it for a generic solution.
â AKX
Aug 8 at 10:00
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
@AKX I'll modify the code a bit and time without function call over head. Well, if I can find an elegant way to balance the books a bit :)
â roganjosh
Aug 8 at 10:01
1
1
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
@roganjosh I also added a 30% faster implementation. :)
â AKX
Aug 8 at 10:04
add a comment |Â
up vote
3
down vote
You can use the following function:
from itertools import filterfalse, tee
def fork(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))
Source: itertools
add a comment |Â
up vote
3
down vote
You can use the following function:
from itertools import filterfalse, tee
def fork(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))
Source: itertools
add a comment |Â
up vote
3
down vote
up vote
3
down vote
You can use the following function:
from itertools import filterfalse, tee
def fork(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))
Source: itertools
You can use the following function:
from itertools import filterfalse, tee
def fork(pred, iterable):
'Use a predicate to partition entries into false entries and true entries'
t1, t2 = tee(iterable)
return list(filterfalse(pred, t1)), list(filter(pred, t2))
Source: itertools
answered Aug 8 at 9:22
![](https://i.stack.imgur.com/peTUC.png?s=32&g=1)
![](https://i.stack.imgur.com/peTUC.png?s=32&g=1)
stasdeep
669414
669414
add a comment |Â
add a comment |Â
up vote
2
down vote
I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:
def myFunc(iterable, func):
first = [i for i in iterable if func(i)]
second = [i for i in iterable if not func(i)]
return first,second
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)
print(even_numbers) # [2, 4]
print(odd_numbers) # [1, 3]
add a comment |Â
up vote
2
down vote
I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:
def myFunc(iterable, func):
first = [i for i in iterable if func(i)]
second = [i for i in iterable if not func(i)]
return first,second
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)
print(even_numbers) # [2, 4]
print(odd_numbers) # [1, 3]
add a comment |Â
up vote
2
down vote
up vote
2
down vote
I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:
def myFunc(iterable, func):
first = [i for i in iterable if func(i)]
second = [i for i in iterable if not func(i)]
return first,second
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)
print(even_numbers) # [2, 4]
print(odd_numbers) # [1, 3]
I did not find anything in standard library performing what you want. I suggest you this user-defined implementation, which is not optimized at all but very simple and easy to read:
def myFunc(iterable, func):
first = [i for i in iterable if func(i)]
second = [i for i in iterable if not func(i)]
return first,second
numbers = [1, 2, 3, 4]
even_numbers, odd_numbers = myFunc(numbers, lambda x: x % 2 == 0)
print(even_numbers) # [2, 4]
print(odd_numbers) # [1, 3]
answered Aug 8 at 9:27
![](https://i.stack.imgur.com/leDO2.jpg?s=32&g=1)
![](https://i.stack.imgur.com/leDO2.jpg?s=32&g=1)
Laurent H.
3,8261530
3,8261530
add a comment |Â
add a comment |Â
up vote
2
down vote
Full code following @jonrsharpe suggestion.
import itertools
def fork(iterable):
"Returns list of even, odd elements of a list"
t1, t2 = itertools.tee(iterable)
pred = lambda i: i % 2 == 0
return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))
odd, even = fork([1,2,3,4,5])
print(odd)
print(even)
Alternative numpy version which might be faster for big arrays
import numpy as np
def fork(iterable):
"Returns array of even, odd elements of an array"
iterable_array = np.asarray(iterable)
mask = (iterable_array % 2 == 0)
return iterable_array[~mask], iterable_array[mask]
add a comment |Â
up vote
2
down vote
Full code following @jonrsharpe suggestion.
import itertools
def fork(iterable):
"Returns list of even, odd elements of a list"
t1, t2 = itertools.tee(iterable)
pred = lambda i: i % 2 == 0
return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))
odd, even = fork([1,2,3,4,5])
print(odd)
print(even)
Alternative numpy version which might be faster for big arrays
import numpy as np
def fork(iterable):
"Returns array of even, odd elements of an array"
iterable_array = np.asarray(iterable)
mask = (iterable_array % 2 == 0)
return iterable_array[~mask], iterable_array[mask]
add a comment |Â
up vote
2
down vote
up vote
2
down vote
Full code following @jonrsharpe suggestion.
import itertools
def fork(iterable):
"Returns list of even, odd elements of a list"
t1, t2 = itertools.tee(iterable)
pred = lambda i: i % 2 == 0
return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))
odd, even = fork([1,2,3,4,5])
print(odd)
print(even)
Alternative numpy version which might be faster for big arrays
import numpy as np
def fork(iterable):
"Returns array of even, odd elements of an array"
iterable_array = np.asarray(iterable)
mask = (iterable_array % 2 == 0)
return iterable_array[~mask], iterable_array[mask]
Full code following @jonrsharpe suggestion.
import itertools
def fork(iterable):
"Returns list of even, odd elements of a list"
t1, t2 = itertools.tee(iterable)
pred = lambda i: i % 2 == 0
return list(filter(pred, t2)), list(itertools.filterfalse(pred, t1))
odd, even = fork([1,2,3,4,5])
print(odd)
print(even)
Alternative numpy version which might be faster for big arrays
import numpy as np
def fork(iterable):
"Returns array of even, odd elements of an array"
iterable_array = np.asarray(iterable)
mask = (iterable_array % 2 == 0)
return iterable_array[~mask], iterable_array[mask]
edited Aug 8 at 9:32
answered Aug 8 at 9:19
user2653663
875713
875713
add a comment |Â
add a comment |Â
up vote
2
down vote
The simplest possible implementation would be probably
def partition(xs, cond):
res = ,
for x in xs:
res[not cond(x)].append(x)
return res
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
add a comment |Â
up vote
2
down vote
The simplest possible implementation would be probably
def partition(xs, cond):
res = ,
for x in xs:
res[not cond(x)].append(x)
return res
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
add a comment |Â
up vote
2
down vote
up vote
2
down vote
The simplest possible implementation would be probably
def partition(xs, cond):
res = ,
for x in xs:
res[not cond(x)].append(x)
return res
The simplest possible implementation would be probably
def partition(xs, cond):
res = ,
for x in xs:
res[not cond(x)].append(x)
return res
answered Aug 8 at 10:13
![](https://i.stack.imgur.com/1Cvf7.png?s=32&g=1)
![](https://i.stack.imgur.com/1Cvf7.png?s=32&g=1)
georg
139k30189286
139k30189286
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
add a comment |Â
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
Wouldn't the simplest possible implementation be the one they're already using, just packaged in a function? This ends up taking twice as long in my tests, despite the single pass. Though I like the code for an approach I haven't thought of before :)
â roganjosh
Aug 8 at 10:17
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
@roganjosh: sure, that's easy to optimize if needed
â georg
Aug 8 at 10:19
add a comment |Â
up vote
0
down vote
You can create your own function:
l = [1, 2, 3, 4]
def fork(l,key):
return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
print(even_numbers)
print(odd_numbers)
Output:
[2, 4]
[1, 3]
add a comment |Â
up vote
0
down vote
You can create your own function:
l = [1, 2, 3, 4]
def fork(l,key):
return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
print(even_numbers)
print(odd_numbers)
Output:
[2, 4]
[1, 3]
add a comment |Â
up vote
0
down vote
up vote
0
down vote
You can create your own function:
l = [1, 2, 3, 4]
def fork(l,key):
return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
print(even_numbers)
print(odd_numbers)
Output:
[2, 4]
[1, 3]
You can create your own function:
l = [1, 2, 3, 4]
def fork(l,key):
return list(filter(key,l)), [i for i in l if i not in list(filter(key,l))]
even_numbers, odd_numbers = fork(l, lambda x: x % 2 == 0)
print(even_numbers)
print(odd_numbers)
Output:
[2, 4]
[1, 3]
answered Aug 8 at 9:23
![](https://i.stack.imgur.com/QvpSg.png?s=32&g=1)
![](https://i.stack.imgur.com/QvpSg.png?s=32&g=1)
U9-Forward
5,7532428
5,7532428
add a comment |Â
add a comment |Â
10
Normally this is called a "partition", there's a recipe in
itertools
for it.â jonrsharpe
Aug 8 at 9:09