user16414300
user16414300

Reputation:

Python Using While loop avoid duplicate print

I am using Python Selenium to parse some live data (Bets) , I am use While loop this is some logic from my code

def parse():
    while True:
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        print(x)

This code working but output is

1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
1.54x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x
13.5x

What is best way to get only one print? for example like this

1.54x
13.5x

Upvotes: 1

Views: 1272

Answers (5)

TERMINATOR
TERMINATOR

Reputation: 1248

You can assign a second variable (y) to the original variable (x) and then assign a new value to x. Then, in an if statement check if they aren't equal (!=).

The code:

def parse():
    x = ''
    while True:
        y = x
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        if y != x:
            print(x)

Upvotes: 2

Ram
Ram

Reputation: 4779

Use a set for faster lookups instead of list.

Since in your question there are only two values, it won't be much of a difference looking up in list and a set. But if there are n values,

list will take O(n) time to lookup

set will take just O(1) time to lookup

def parse():
    s = set()
    while True:
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        if x not in s:
           s.add(x)
           print(x)

Upvotes: 0

Muhammad Shoaib
Muhammad Shoaib

Reputation: 86

You have to store the uniquely received values. Later you can check if the newly received value already exists then do not print this value otherwise print it to console.

def parse():
    stored_data = []
    while True:
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        if x not in stored_data:
            print(x)
            stored_data.append(x)

Upvotes: 0

Red
Red

Reputation: 27547

As you only want every value to be printed once, you can define a list, xs.

For each x defined, if the value of the x is already in the xs list, don't print or append the value of x to xs; else, print the value of x and append the value of x to xs:

def parse():
    xs = []
    while True:
        x = driver.find_element_by_xpath('//*[@id="bets-history"]/li[0]').text
        if x not in xs:
            xs.append(x)
            print(x)

Upvotes: 1

Yaroslav  Kornachevskyi
Yaroslav Kornachevskyi

Reputation: 1218

data = ['1.54x','1.54x','1.54x','1.54x','1.54x','1.54x','1.54x','1.54x','13.5x','13.5x','13.5x','13.5x','13.5x','13.5x','13.5x','13.5x']

previous_value = ''
for value in data:
    if value != previous_value:
        print(value)
        previous_value = value

Upvotes: 1

Related Questions