[英]Print something just once in a for loop
我有一個正在使用英雄聯盟API的機器人。 我只想從特定的比賽中檢索一些統計信息。 我的代碼可以工作,但是它又長又重復,我想清理它。 現在,代碼的主要功能正在運行,但是在我將其放入機器人中之前,我需要進行一些測試。 現在,這是代碼,我將對其進行解釋。
for i in range(0, 9):
num += 1
i = r_match['participants'][num]
e_name = i['summonerName']
e_id = i['summonerId']
team_id = i['teamId']
r_team = requests.get("https://lan.api.pvp.net/api/lol/lan/v2.5/league/by-summoner/{}/"
"entry?api_key=".format(e_id)).json()
x = r_team["{}".format(e_id)][0]
e_tier = x['tier']
e_div = x['entries'][0]['division']
if team_id == 100:
print("Blue team")
print(e_name, e_tier, e_div)
elif team_id == 200:
print("Red team")
print(e_name, e_tier, e_div)
因此,這部分代碼獲取了比賽參與者的姓名,獲得了他們的ID,並使用該ID找到了其他一些統計信息。 有兩支隊伍。 在Json響應中,每個團隊都有一個ID。 您可以在此處看到100和200:
if team_id == 100:
print("Blue team")
print(e_name, e_tier, e_div)
elif team_id == 200:
print("Red team")
print(e_name, e_tier, e_div)
我要做的是在條件滿足時只打印一次“藍隊”和“紅隊”。 這樣一來,我就可以很好地將其打印為該機器人正在工作的聊天室,但是每次我運行代碼時,它都會為比賽的每個參與者打印“藍隊”或“紅隊”,比方說:
Blue Team
player 1
Blue Team
player 2...
依此類推,直到總共打印出10個播放器。 我想做的是:
Blue Team
player1
player2
player3
player4
player5
Red Team
player6
player7
player8
player9
player10
就是這樣。 謝謝你的幫助 :)
ids_seen = set ()
for i in range(0, 9):
num += 1
i = r_match['participants'][num]
e_name = i['summonerName']
e_id = i['summonerId']
team_id = i['teamId']
r_team = requests.get("https://lan.api.pvp.net/api/lol/lan/v2.5/league/by-summoner/{}/"
"entry?api_key=".format(e_id)).json()
x = r_team["{}".format(e_id)][0]
e_tier = x['tier']
e_div = x['entries'][0]['division']
if team_id == 100:
if not team_id in ids_seen:
print("Blue team")
print(e_name, e_tier, e_div)
elif team_id == 200:
if not team_id in ids_seen:
print("Red team")
print(e_name, e_tier, e_div)
ids_seen.add (team_id)
我會存儲一本字典,然后在以后打印出所有播放器。
teams = {}
for _ in range(9):
num += 1
i = r_match['participants'][num]
e_name = i['summonerName']
e_id = i['summonerId']
team_id = i['teamId']
if team_id not in teams:
teams[str(team_id)] = list()
r_team = requests.get("https://lan.api.pvp.net/api/lol/lan/v2.5/league/by-summoner/{}/"
"entry?api_key=".format(e_id)).json()
x = r_team["{}".format(e_id)][0]
e_tier = x['tier']
e_div = x['entries'][0]['division']
teams[str(team_id)].append( (e_name, e_tier, e_div,) )
# Outside loop
print("Blue team")
for data in teams['100']:
print(*data)
print("Red team")
for data in teams['200']:
print(*data)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.