Reputation:
I make a discord bot and one funtion is that you can get stats for champions from the game League of Legends, now i have 3 code parts that are actually the same, there are just 2 things that are different. Is it possible to make a for loop or something like that to put them in on function?
#winrate
elem = soup.find_all("tr", {"id": "statistics-win-rate-row"})
table = str(elem[0])
tablerow = table.splitlines()
for item in tablerow:
if "%" in item:
item = item.replace(" ", "")
winrate = item
break
#playrate
elem = soup.find_all("tr", {"id": "statistics-play-rate-row"})
table = str(elem[0])
tablerow = table.splitlines()
for item in tablerow:
if "%" in item:
item = item.replace(" ", "")
playrate = item
break
#banrate
elem = soup.find_all("tr", {"id": "statistics-ban-rate-row-row"})
table = str(elem[0])
tablerow = table.splitlines()
for item in tablerow:
if "%" in item:
item = item.replace(" ", "")
banrate = item
break
Upvotes: 2
Views: 53
Reputation: 4382
When facing such problems try to search for the common parts of your code, I mean, things that are doing repeated worked, but named differently. You have remarked yourself that "3 code parts area actually the same". That is exactly a good case for refactoring it into a function. Here is my suggestion:
def get_item_for(id):
elem = soup.find_all("tr", {"id": id})
table = str(elem[0])
tablerow = table.splitlines()
for item in tablerow:
if "%" in item:
return item.replace(" ", "")
winrate = get_item_for("statistics-win-rate-row")
playrate = get_item_for("statistics-play-rate-row")
banrate = get_item_for("statistics-ban-rate-row-row")
Upvotes: 1
Reputation: 674
I would suggest making a function which has an argument which has a flag which triggers special operation, like:
def function(flag):
# code
if(flag == 1):
winrate = item
elif(flag == 2):
playrate = item
elif(flag == 3):
banrate = item
#rest of the code
Upvotes: 0