Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to remove a tuple in an integer tuple, if its last element is "0", using Python itertools?

I have the following code to create a tuple contains multiple tuple with integer pairs:

iterable = (
    tuple(zip([0, 1, 2], _))
    for _ in product(range(9), repeat=3)
)
next(iterable)  # First element is not needed
print(list(iterable))

# This code produces: [((0, 0), (1, 0), (2, 1)), ... , ((0, 8), (1, 8), (2, 8))]

But I need that if last element of a tuple is "0" (e.g. (0, 0) or (2, 0)), I have to remove that tuple. So new list should be like this:

[((2, 1),), ... , ((1, 2), (2, 7)), ((1, 2), (2, 8)), ... , ((0, 8), (1, 8), (2, 8))]

I actually achieved this goal by the following code but it is not the correct way I think, I don’t know:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x = ()
for i in iterable:
    y = ()
    for j in i:
        if j[-1] != 0:
            y += (j,)
    x += (y,)
print(list(x))

How can I do do this with itertools and in one line, if possible? If needed, I can change the code at the top of this question, to create the desired list one line.

Thank you.

>Solution :

Use filter() to remove the elements ending in 0 from the result of zip().

iterable = (
    tuple(filter(lambda x: x[-1] != 0, zip([0, 1, 2], _)))
    for _ in product(range(9), repeat=3)
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading