Marzipan Jones
Marzipan Jones

Reputation: 25

Function which returns either the positive or negative elements of the list

I'm trying to create a splitList function that takes an option as input and returns either positive or negative elements of the list.

So far this is all I have:

def splitList([1,-3,5,7,-9,-11,10,2,-4], option)

Upvotes: 1

Views: 1389

Answers (4)

Terrymight
Terrymight

Reputation: 79

Here's one approach:

def split_list():
    pos = []
    neg = []

     for i in alist:
        if i < 0:
            pos.append(i)
     print pos
     for i in alist:
        if i > 0:
            neg.append(i)
     print neg



def main():
    alist = [54,26,-93,-17,-77,31,44,55,20]
    manipulate_data(alist)

if __name__ == '__main__':
    main()

Upvotes: 0

pillmuncher
pillmuncher

Reputation: 10162

Here's another alternative:

import operator

def split_list(iterator, positive=True, sign_test=(operator.lt, operator.gt)):
    return [i for i in iterator if sign_test[positive](i, 0)]

Call it like so:

>>> split_list([1, -2, 4, 0, -4], False)
[-2, -4]

or:

>>> split_list([1, -2, 4, -0, 4], True, (operator.lt, operator.ge))
[1, 4, 0]

Upvotes: 0

Matthew Trevor
Matthew Trevor

Reputation: 14952

Here's a slightly DRYer alternative:

import operator

def split_list(iterator, positive=True):
    sign_test = operator.gt if positive else operator.lt
    return [i for i in iterator if sign_test(i, 0)]

If you want it to return nonpositive/nonnegative instead, you can replace gt & lt with ge and le.

Upvotes: 2

hexparrot
hexparrot

Reputation: 3417

I'd recommend you use more meaningful words to describe your intent for positive or negative integers. Here's an example function for you:

def split_list(data_set, positive=True):
    if positive:
        return [i for i in data_set if i > 0]
    return [i for i in data_set if i < 0]

example = [1,-3,5,7,-9,-11,0,2,-4]
print split_list(example, True)
print split_list(example, False)

returns:

[1, 5, 7, 2]
[-3, -9, -11, -4]

As a side note, this example assumes 0 is considered neither positive nor negative--you can easily adjust the > or < to >= or <= to adjust your particular needs.

Upvotes: 1

Related Questions