Moondra
Moondra

Reputation: 4511

Returning my printed output in pairs as tuples?

for div in soup.find_all('table', class_="W(100%)"):
       for y in div.find_all('td'):
           print (y.text)

returns an output of:

Previous Close
38.08
Open
38.23
Bid
37.67 x 100
Ask
38.16 x 500
Day's Range
37.35 - 38.25
52 Week Range
23.50 - 40.92
Volume
29,152
Avg. Volume
118,446
Market Cap
1.66B

I want to return the output as

(Previous Close, 38.08)
(Open, 38.23)
(Bid, 37.67 x 100)

I honestly have no idea how to tackle this. I thought about implementing an and odd and even counter, but even then, how would I join the previous entry with the next entry?

Upvotes: 1

Views: 60

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121714

Look for rows (<tr> elements), not cells; you can then group cells per row:

for row in soup.select('table.W(100%) tr'):
    columns = tuple(cell.text for cell in row.find_all('td'))
    print(columns)

I used the CSS select() method to concisely request all table rows for your given table.

Upvotes: 2

Xoniterfos
Xoniterfos

Reputation: 21

You can do this by going through every even index and taking that element and the one after it, and putting them into a pair. The following would work as a generator:

def pairs(array):
    for i in range(0, len(array), 2):
        yield (array[i], array[i + 1])

Alternatively, if you want the function to return a list of the pairs:

def pairs(array):
    output = []
        for i in range(0, len(array), 2):
            output.append((array[i], array[i + 1])

Or, for a simpler (but less readable) program:

def pairs(array):
    return map(lambda index: (array[index], array[index + 1]), range(0, len(array), 2))

If you only want to output it in that format, there's a different way to do that directly, other than converting it to tuples and outputting those:

def outputPairs(array):
    for i in range(0, len(array), 2):
        print("(" + str(array[i]) + ", " + str(array[i + 1]) + ")")

Upvotes: 2

Related Questions