samedi 12 mai 2018

How to remove list element using while loop python

I open a web page to get the names of the cluster1(p1, p2). I am not sure how many times I need to open a web page to get these cluster1 names. So, I am using a while loop, it will remove the p1 or p2 whichever the value is obtained from web page.

When I open a web page, I'll get p1 or p2 and that value will be stored in new[-1]. If this value is in cluster1, it will execute the other test functions and that value will be removed from cluster1.

dc_elm = driver.find_element_by_xpath('/html/body/div[2]/span[2]').text

new = unicodedata.normalize('NFKD', dc_elm).encode('ascii', 'ignore').split()

cluster1 =[ 'p1', 'p2'] 

 while len(cluster1) != 0:
    print("Length of cluster1 before:", len(cluster1))
    # for i in range(10):

    if new[-1] in cluster1:
        print(new[-1] + " is in cluster1.")
        test1()
        test2()
        new_ver_names.append(new[-1])
        cluster1.remove(new[-1])
        print("Length of cluster1 after:", len(cluster1))
    else:
            print(new[-1] + " portal version is not listed.")
            driver.quit()
            break

My exception is, when value is removed, control should go back to while loop and start again until len(cluster1) is 0. And, if the value is not in cluster1, else past should execute. But, when I remove cluster1.remove(new[-1]), else part also gets executed.

I checked other answers where it is mentioned we can't remove items from a list while iterating over it and tried list comprehension. But, couldn't make it work.

I tried lst = [(teset1(), test2()) for i in range(len(cluster1)) if new[-1] in cluster1]

Any help is really appreciated.

Thank you.

Aucun commentaire:

Enregistrer un commentaire