w3resource

Python: Extract non_zero block from a given integers of list

Python Itertools: Exercise-44 with Solution

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]]

Python Code Editor:


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

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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/itertools/python-itertools-exercise-44.php