Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Split a list of integers into positive and negative

I'm learning python and i wanted to know whats the way to to split a list like :

A = [1, -3, -2, 8, 4, -5, 6, -7]

into two lists, one containing positive and the other one containing negative integers :

B = [1, 8, 4, 6]
C = [-3, -2, -5, -7]
like image 654
Irfan Avatar asked Oct 26 '25 03:10

Irfan


1 Answers

You can do this in O(n) using a defaultdict():

In [3]: from collections import defaultdict

In [4]: d = defaultdict(list)

In [5]: for num in A:
   ...:     if num < 0:
   ...:         d['neg'].append(num)
   ...:     else: # This will also append zero to the positive list, you can change the behavior by modifying the conditions 
   ...:         d['pos'].append(num)
   ...:         

In [6]: d
Out[6]: defaultdict(<class 'list'>, {'neg': [-3, -2, -5, -7], 'pos': [1, 8, 4, 6]})

Another way is using two separate list comprehensions (not recommended for long lists):

>>> B,C=[i for i in A if i<0 ],[j for j in A if j>0]
>>> B
[-3, -2, -5, -7]
>>> C
[1, 8, 4, 6]

Or as a purely functional approach you can also use filter as following:

In [19]: list(filter((0).__lt__,A))
Out[19]: [1, 8, 4, 6]

In [20]: list(filter((0).__gt__,A))
Out[20]: [-3, -2, -5, -7]
like image 119
Mazdak Avatar answered Oct 27 '25 16:10

Mazdak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!