any modules having a function to partition a list by predicate provided?
krister.svanlund at gmail.com
Tue Apr 20 00:29:43 EDT 2010
On Tue, Apr 20, 2010 at 3:40 AM, segunai <osk.iru at gmail.com> wrote:
> On 4월20일, 오전10시16분, Chris Rebert <c... at rebertia.com> wrote:
>> On Mon, Apr 19, 2010 at 6:00 PM, knifenomad <knifeno... at gmail.com> wrote:
>> > i know it's not very hard to get that solution.
>> > just by implementing simple function like below.
>> > def partition(target, predicate):
>> > """
>> > split a list into two partitions with a predicate
>> > provided.
>> > any better ideas? :)
>> > """
>> > true = 
>> > false= 
>> > for item in target:
>> > if predicates(item):
>> > true.append(item)
>> > else:
>> > false.append(item)
>> > return true, false
>> > but i wonder if there's another way to do this with standard libraries
>> > or .. built-ins.
>> > if it's not, i'd like the list objects to have partition method like
>> > string module has.
>> (A) str.partition() has a /completely/ different meaning from your partition()
>> (B) You'd probably have better luck getting it added to the itertools
>> module since the concept is applicable to all iterables.
> yep, my mistake. i shouldn't have compared it to string's partition().
> i just wanted that convenience string.partition() has as a built-in.
> anyway, thanks for itertools. :)
The way I would do it is probably apply filter to the list:
>>> def f(x): return x % 2 != 0 and x % 3 != 0
>>> filter(f, range(2, 25))
[5, 7, 11, 13, 17, 19, 23]
More information about the Python-list