Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Taking Apart A List Python

If I have a list like:

X = [0, 2, 3, 4.0, 1, 0, 3, 0, 0, 0, 2, 1, 5, 2, 6, 0, 2.2, 1]

How would I write code in python that takes this list and finds the number of consecutive positive numbers and then makes a list that has lists of each of those consecutive numbers in it.

for example this example of x would return a number 4 and it would also return:

[[ 2, 3, 4.0, 1], [3], [ 2, 1, 5, 2, 6], [ 2.2, 1]]. 

I wrote this to find all the zeros but I do not know where to go from there:

 zeros = []
 for i in range(0,len(World)):
      if z[i]==0: 
          zeros.append(i)
like image 659
Laura Avatar asked Jul 20 '26 05:07

Laura


1 Answers

There is no need to fine the zeros. You can simply loop over your list and put the positive numbers in a temporary list until you encounter with a zero, but as a more pythonic approach for such tasks you can use itertools.groupby :

>>> from itertools import groupby
>>> [list(g) for k,g in groupby(X,key=lambda x:x>0) if k]
[[2, 3, 4.0, 1], [3], [2, 1, 5, 2, 6], [2.2, 1]]

If you want to do it without itertools module you can use following function which works based on preceding explanation and yields the temp list every time it encounter a zero, and at last returns a generator contains list of positive numbers which you can convert it to a list by calling the list function :

>>> def grouper(li,temp=[]):
...    for i in li:
...        if i>0:
...           temp.append(i)
...        else:
...            if temp: yield temp
...            temp=[]
...    if temp : yield temp
...

Demo:

>>> list(grouper(X))
[[2, 3, 4.0, 1], [3], [2, 1, 5, 2, 6], [2.2, 1]]
like image 109
Mazdak Avatar answered Jul 21 '26 19:07

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!