Search code examples
pythonliststacked

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)

Solution

  • You do not need to find out the indices of zeroes before-hand. You can simply keep another temporary list holding the values that are positive (greater than 0) since the last time 0 was encountered. And then when you encounter a 0 , append that temporary list to the result list, and change that temporary list to a new list. Example -

    result = []
    temp = []
    for i in X:
        if i <= 0:
            if temp:
                result.append(temp)
                temp = []
        else:
            temp.append(i)
    if temp:
        result.append(temp)
    

    Demo -

    >>> result = []
    >>> temp = []
    >>> for i in X:
    ...     if i <= 0:
    ...         if temp:
    ...             result.append(temp)
    ...             temp = []
    ...     else:
    ...         temp.append(i)
    ...
    >>> if temp:
    ...     result.append(temp)
    ...
    >>> result
    [[2, 3, 4.0, 1], [3], [2, 1, 5, 2, 6], [2.2, 1]]