Home > Software engineering >  How to compare a list with the result from an iteration?
How to compare a list with the result from an iteration?

Time:10-01

I have the following code block:

Game_names = ['Game1', 'Game2', 'Game3', 'Game4', 'Game5']
for i in driver.find_elements_by_id("com.project.ProjectName:id/itemContainer"):
    for title in i.find_elements_by_id("com.project.ProjectName:id/title"):
        print('Game titles are: '   title.text)
         if Game_names == title.text:
             print('Games titles are correct')
         else:
            print('Games titles are not correct')

I need to check if the game names are correct.

Can anyone help me with that? Thanks in advance.

CodePudding user response:

To check that two iterables are equal, use all():

a = [0,1,2]
b = (0,1,2)
all(x == y for x, y in zip(a,b))

In your case you will have to extract the text:

titles = i.find_elements_by_id("com.project.ProjectName:id/title")
all(x==y.text for x,y in zip(gameTitles, titles))

Unless the titles really are all in each element, which case presumably you want to split them:

titles = i.find_elements_by_id("com.project.ProjectName:id/title")
for title in titles:
    assert all(x==y.strip() for x,y in zip(gameTitles, title.text.split())

Note that if order could change, you need to sort first, either by sorting in-place or by iterating sorted(thing)

Checking one element

If you only want to check whether an element is in the list, just do:

for title in titles:
    if title.text.strip() in GameTitles:
        ...
  • Related