vendredi 24 mars 2017

Is the if statement condition mutually-exclusive to multiple variables?

Let's say that I have three lists and want to add all elements that are integers to a list named int_list:

test1 = [1, 2, 3, "b", 6]
test2 = [1, "foo", "bar", 7]
test3 = ["more stuff", 1, 4, 99]
int_list = []

I know that I can do the following code to append all integers to a new list:

for elem1, elem2, elem3 in zip(test1, test2, test3):
    if elem1 is int:
        int_list.append(elem1)
    if elem2 is int:
        int_list.append(elem2)
    if elem3 is int:
        int_list.append(elem3)

Is there anyway that I can merge the if statements into one conditional statement? Or make it less code? Is there a more pythonic way to do this? I tried doing the following code, but it would include elements that were not integers:

for elem1, elem2, elem3 in zip(test1, test2, test3):
        if (elem1 is int, elem2 is int, elem3 is int):
            int_list.append(elem1)
            int_list.append(elem2)
            int_list.append(elem3)

Thank you in-advanced for your help!

Aucun commentaire:

Enregistrer un commentaire