如何在Python中组合代码?
我制作了一个discord机器人,一个功能是你可以从游戏《传奇联盟》中获得冠军的数据,现在我有3个代码部分实际上是相同的,只有两个不同。有没有可能制作一个for循环或类似的东西来将它们放入函数中如何在Python中组合代码?,python,Python,我制作了一个discord机器人,一个功能是你可以从游戏《传奇联盟》中获得冠军的数据,现在我有3个代码部分实际上是相同的,只有两个不同。有没有可能制作一个for循环或类似的东西来将它们放入函数中 #winrate elem = soup.find_all("tr", {"id": "statistics-win-rate-row"}) table = str(elem[0]) tablerow = table.splitlines() for item in tablerow: if "
#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
我建议创建一个具有参数的函数,该参数具有触发特殊操作的标志,如:
def function(flag):
# code
if(flag == 1):
winrate = item
elif(flag == 2):
playrate = item
elif(flag == 3):
banrate = item
#rest of the code
当遇到这样的问题时,试着搜索代码的公共部分,我的意思是,重复进行的工作是有效的,但命名不同。您已经注意到“3个代码部分区域实际上是相同的”。这正是将其重构为函数的好例子。以下是我的建议:
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")