w3resource

Python: Extract non_zero block from a given integers of list


44. Extract Non-zero Block

Write a Python program to extract a non-zero block from a given integer list.

Sample Solution:

Python Code:

import itertools as it
def test(lst):
    result = [ list(x[1]) for x in it.groupby(lst, lambda x: x == 0) if not x[0] ]
    return result
nums = [3,4,6,2,0,0,0,0,0,0,6,7,6,9,10,0,0,0,0,0,7,4,4,0,0,0,0,0,0,5,3,2,9,7,1]
print("\nOriginal list:")
print(nums)
print("\nExtract non_zero block from a given integers of list:")
print(test(nums))

Sample Output:

Original list:
[3, 4, 6, 2, 0, 0, 0, 0, 0, 0, 6, 7, 6, 9, 10, 0, 0, 0, 0, 0, 7, 4, 4, 0, 0, 0, 0, 0, 0, 5, 3, 2, 9, 7, 1]

Extract non_zero block from a given integers of list:
[[3, 4, 6, 2], [6, 7, 6, 9, 10], [7, 4, 4], [5, 3, 2, 9, 7, 1]]

For more Practice: Solve these Related Problems:

  • Write a Python program to extract the first contiguous block of non-zero numbers from a given list using itertools.takewhile.
  • Write a Python program to create an iterator that skips over zeros and then groups non-zero elements into a block using itertools.groupby.
  • Write a Python program to split a list into blocks separated by zeros and then select the longest non-zero block.
  • Write a Python program to use itertools.dropwhile to ignore leading zeros and then collect the next sequence of non-zero numbers into a list.

Go to:

Previous: Write a Python program to find maximum difference pair in a given list.

Next: Python Filter Exercises Home.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.