Michael
Michael

Reputation: 351

Only looping through even numbers

I am new to programming so forgive me if this is basic.

Below is part of my code for extracting Home and Away odds from many different bookmakers for a basketball match. If I just loop through every element in the range, I am left with home and away odds all in one column, however, I want a separate column for home and away odds.

num_page_items = len(odds)
for i in range(num_page_items):
    Home = (odds[2*i].text)
    Away = (odds[2*i-1].text)
print(Home,Away)

My desired outcome is to display the home team odds next to the away team odds separated by a comma. My code achieves this, however I believe it is not a great way of doing it as it technically runs into an error at the end (even though all of the data I'm after still displays).

How can I clean this up? Thanks

Upvotes: 1

Views: 2913

Answers (4)

notback
notback

Reputation: 41

The itemgetter in the standard module operator is designed to select list contents. Fast, suitable for regular selection.

from operator import itemgetter
odds=[1,2,3,4,5,6]
num_page_items = len(odds)

getHome = itemgetter(*range(0,num_page_items,2))
getAway = itemgetter(*range(1,num_page_items,2))
Home = getHome(odds)
Away = getAway(odds)
print(Home)
print(Away)

Output:

(1, 3, 5)
(2, 4, 6)

Upvotes: 0

Devanshu Misra
Devanshu Misra

Reputation: 813

Another way to go is to do a check inside the for-loop whether i is odd or even. Just a work around of Shobhit Verma's answer.

num_page_items = len(odds)
for i in range(num_page_items):
    if i % 2 == 0:                    #This is a sanity check to see if i is odd or even
        Home = odds[i].text
    else:
        Away = odds[i].text

Upvotes: 0

blhsing
blhsing

Reputation: 106553

You can create an iterable with a generator expression to extract the text attribute from the odd objects, and then pair them by zipping the iterable with itself, so that you can iterate through it to unpack Home and Away:

i = (odd.text for odd in odds)
for Home, Away in zip(i, i):
    print(Home, Away)

Upvotes: 2

Shobhit Verma
Shobhit Verma

Reputation: 2261

num_page_items = len(odds)
for i in range(0, num_page_items, 2):
    Home = odds[i].text  # Starts from 0, goes till num_page_items, incrementing by 2 (even indices)
for i in range(1, num_page_items, 2):
    Away = odds[i].text # Starts from 1, goes till num_page_items, incrementing by 2 (odd indices)

You run into an IndexError, since you access an element at index 2*i, where i iterates over values from 0 to the size of the list. For eg, if size is 10, you will end up trying to access odds[2*i] for i = 5, 6, 7... , the index of which is out of bounds

Upvotes: 1

Related Questions