Quantcast
Channel: How can I partition (split up, divide) a list based on a condition? - Stack Overflow
Browsing latest articles
Browse All 41 View Live

Answer by Bharel for How can I partition (split up, divide) a list based on a...

Simple generator version, holds the least amount of values possible in memory and calls pred only once:from collections import dequefrom typing import Callable, TypeVar, Iterable_T = TypeVar('_T')def...

View Article


Answer by JustinFisher for How can I partition (split up, divide) a list...

This question has many answers already, but all seem inferior to my favorite approach to this problem, which iterates through and tests each item just once, and uses the speed of list-comprehension to...

View Article


Answer by double0darbo for How can I partition (split up, divide) a list...

I turned to numpy to solve this to limit lines and make into a simple function.I was able to get a conditional met, separating a list into two, using np.where to separate out a list. This works for...

View Article

Answer by ChaimG for How can I partition (split up, divide) a list based on a...

Clear and fastThis list comprehension is simple to read and fast. Exactly what the OP asked for.set_good_vals = set(good_vals) # Speed boost.good = [x for x in my_list if x in set_good_vals]bad = [x...

View Article

Answer by Ymareth for How can I partition (split up, divide) a list based on...

A generator based version, if you can put up with one or maybe two reversals of the original list.A setup...random.seed(1234)a = list(range(10))random.shuffle(a)a[2, 8, 3, 5, 6, 4, 9, 0, 1, 7]And the...

View Article


Answer by thehappycheese for How can I partition (split up, divide) a list...

The previous answers don't seem to satisfy all four of my obsessive compulsive ticks:Be as lazy as possible,Evaluate the original Iterable only onceEvaluate the predicate only once per itemProvide nice...

View Article

Answer by scp10011 for How can I partition (split up, divide) a list based on...

Use Boolean logic to assign data to two arrays>>> images, anims = [[i for i in files if t ^ (i[2].lower() in IMAGE_TYPES) ] for t in (0, 1)]>>> images[('file1.jpg', 33,...

View Article

Answer by Trylks for How can I partition (split up, divide) a list based on a...

You can do lazy functional programming in Python, like this:partition = lambda l, c: map( lambda iii: (i for ii in iii for i in ii), zip(*(([], [e]) if c(e) else ([e], []) for e in l)))Functional...

View Article


Answer by Phil B for How can I partition (split up, divide) a list based on a...

good.append(x) if x in goodvals else bad.append(x)This elegant and concise answer by @dansalmo showed up buried in the comments, so I'm just reposting it here as an answer so it can get the prominence...

View Article


Answer by Biga for How can I partition (split up, divide) a list based on a...

bad = []good = [x for x in mylist if x in goodvals or bad.append(x)]append returns None, so it works.

View Article

Answer by Shay for How can I partition (split up, divide) a list based on a...

Yet another answer, short but "evil" (for list-comprehension side effects).digits = list(range(10))odd = [x.pop(i) for i, x in enumerate(digits) if x % 2]>>> odd[1, 3, 5, 7, 9]>>>...

View Article

Answer by Chrisjan for How can I partition (split up, divide) a list based on...

images = [f for f in files if f[2].lower() in IMAGE_TYPES]anims = [f for f in files if f not in images]Nice when the condition is longer, such as in your example. The reader doesn't have to figure out...

View Article

Answer by ChaimG for How can I partition (split up, divide) a list based on a...

Elegant and FastInspired by DanSalmo's comment, here is a solution that is concise, elegant, and at the same time is one of the fastest solutions.good_set = set(goodvals)good, bad = [], []for item in...

View Article


Answer by David for How can I partition (split up, divide) a list based on a...

If the list is made of groups and intermittent separators, you can use:def split(items, p): groups = [[]] for i in items: if p(i): groups.append([]) groups[-1].append(i) return...

View Article

Answer by Pavel Ilchenko for How can I partition (split up, divide) a list...

For example, splitting list by even and oddarr = range(20)even, odd = reduce(lambda res, next: res[next % 2].append(next) or res, arr, ([], []))Or in general:def split(predicate, iterable): return...

View Article


Answer by kiran for How can I partition (split up, divide) a list based on a...

Not sure if this is a good approach but it can be done in this way as wellIMAGE_TYPES = ('.jpg','.jpeg','.gif','.bmp','.png')files = [ ('file1.jpg', 33L, '.jpg'), ('file2.avi', 999L, '.avi')]images,...

View Article

Answer by MSeifert for How can I partition (split up, divide) a list based on...

If you don't mind using an external library there two I know that nativly implement this operation:>>> files = [ ('file1.jpg', 33, '.jpg'), ('file2.avi', 999, '.avi')]>>> IMAGE_TYPES...

View Article


Answer by radeklat for How can I partition (split up, divide) a list based on...

Yet another solution to this problem. I needed a solution that is as fast as possible. That means only one iteration over the list and preferably O(1) for adding data to one of the resulting lists....

View Article

Answer by FunkySayu for How can I partition (split up, divide) a list based...

Sometimes, it looks like list comprehension is not the best thing to use !I made a little test based on the answer people gave to this topic, tested on a random generated list. Here is the generation...

View Article

Answer by Gecko for How can I partition (split up, divide) a list based on a...

I think a generalization of splitting a an iterable based on N conditions is handyfrom collections import OrderedDictdef partition(iterable,*conditions):'''Returns a list with the elements that satisfy...

View Article

Answer by doctorzeb8 for How can I partition (split up, divide) a list based...

solutionfrom itertools import teedef unpack_args(fn): return lambda t: fn(*t)def separate(fn, lx): return map( unpack_args( lambda i, ly: filter( lambda el: bool(i) == fn(el), ly)), enumerate(tee(lx,...

View Article


Answer by Hanfei Sun for How can I partition (split up, divide) a list based...

def partition(pred, iterable):'Use a predicate to partition entries into false entries and true entries' # partition(is_odd, range(10)) --> 0 2 4 6 8 and 1 3 5 7 9 t1, t2 = tee(iterable) return...

View Article


Answer by Jim Witschey for How can I partition (split up, divide) a list...

I'd take a 2-pass approach, separating evaluation of the predicate from filtering the list:def partition(pred, iterable): xs = list(zip(map(pred, iterable), iterable)) return [x[1] for x in xs if...

View Article

Answer by Shreyas for How can I partition (split up, divide) a list based on...

Already quite a few solutions here, but yet another way of doing that would be -anims = []images = [f for f in files if (lambda t: True if f[2].lower() in IMAGE_TYPES else anims.append(t) and...

View Article

Answer by emvee for How can I partition (split up, divide) a list based on a...

def partition(pred, seq): return reduce( lambda (yes, no), x: (yes+[x], no) if pred(x) else (yes, no+[x]), seq, ([], []) )

View Article


Answer by Josh Bode for How can I partition (split up, divide) a list based...

Inspired by @gnibbler's great (but terse!) answer, we can apply that approach to map to multiple partitions:from collections import defaultdictdef splitter(l, mapper):"""Split an iterable into multiple...

View Article

Answer by John La Rooy for How can I partition (split up, divide) a list...

Iterate manually, using the condition to select a list to which each element will be appended:good, bad = [], []for x in mylist: (bad, good)[x in goodvals].append(x)

View Article

Answer by jcb for How can I partition (split up, divide) a list based on a...

If your concern is not to use two lines of code for an operation whose semantics only need once you just wrap some of the approaches above (even your own) in a single function:def...

View Article

Answer by sastanin for How can I partition (split up, divide) a list based on...

My take on it. I propose a lazy, single-pass, partition function,which preserves relative order in the output subsequences.1. RequirementsI assume that the requirements are:maintain elements' relative...

View Article



Answer by Shikhar Mall for How can I partition (split up, divide) a list...

Sometimes you won't need that other half of the list.For example:import sysfrom itertools import ifiltertrustedPeople = sys.argv[1].split(',')newName = sys.argv[2]myFriends = ifilter(lambda x:...

View Article

Answer by Alan Isaac for How can I partition (split up, divide) a list based...

I basically like Anders' approach as it is very general. Here's a version that puts the categorizer first (to match filter syntax) and uses a defaultdict (assumed imported).def categorize(func,...

View Article

Answer by kxmh42 for How can I partition (split up, divide) a list based on a...

If you want to make it in FP style:good, bad = [ sum(x, []) for x in zip(*(([y], []) if y in goodvals else ([], [y]) for y in mylist)) ]Not the most readable solution, but at least iterates through...

View Article

Answer by Brian for How can I partition (split up, divide) a list based on a...

itertools.groupby almost does what you want, except it requires the items to be sorted to ensure that you get a single contiguous range, so you need to sort by your key first (otherwise you'll get...

View Article


Answer by dbr for How can I partition (split up, divide) a list based on a...

good = [x for x in mylist if x in goodvals]bad = [x for x in mylist if x not in goodvals]is there a more elegant way to do this?That code is perfectly readable, and extremely clear!# files looks like:...

View Article

Answer by Anders Eurenius for How can I partition (split up, divide) a list...

If you insist on clever, you could take Winden's solution and just a bit spurious cleverness:def splay(l, f, d=None): d = d or {} for x in l: d.setdefault(f(x), []).append(x) return d

View Article

Answer by Ants Aasma for How can I partition (split up, divide) a list based...

Here's the lazy iterator approach:from itertools import teedef split_on_condition(seq, condition): l1, l2 = tee((condition(item), item) for item in seq) return (i for p, i in l1 if p), (i for p, i in...

View Article


Answer by winden for How can I partition (split up, divide) a list based on a...

Problem with all proposed solutions is that it will scan and apply the filtering function twice. I'd make a simple small function like this:def split_into_two_lists(lst, f): a = [] b = [] for elem in...

View Article


Answer by gimel for How can I partition (split up, divide) a list based on a...

For perfomance, try itertools.The itertools module standardizes a core set of fast, memory efficient tools that are useful by themselves or in combination. Together, they form an “iterator algebra”...

View Article

Answer by BJ Homer for How can I partition (split up, divide) a list based on...

Personally, I like the version you cited, assuming you already have a list of goodvals hanging around. If not, something like:good = filter(lambda x: is_good(x), mylist)bad = filter(lambda x: not...

View Article

Answer by RichieHindle for How can I partition (split up, divide) a list...

First go (pre-OP-edit): Use sets:mylist = [1,2,3,4,5,6,7]goodvals = [1,3,7,8,9]myset = set(mylist)goodset = set(goodvals)print list(myset.intersection(goodset)) # [1, 3, 7]print...

View Article

How can I partition (split up, divide) a list based on a condition?

I have some code like:good = [x for x in mylist if x in goodvals]bad = [x for x in mylist if x not in goodvals]The goal is to split up the contents of mylist into two other lists, based on whether or...

View Article

Browsing latest articles
Browse All 41 View Live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>