在for循环中只打印一次

时间:2016-11-12 21:14:10

标签: python

我有一个使用英雄联盟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)

我想做的是打印"蓝队"和#34;红队"满足条件时只需一次。这样我就可以打印出干净利落的机器人工作的聊天,但每次我运行代码时,都会打印出蓝色团队"或者"红队"对于比赛的每个参赛者,请说:

Blue Team
player 1
Blue Team
player 2...

依此类推,直到总共有10名玩家打印出来。我想做的是:

Blue Team
player1
player2
player3
player4
player5

Red Team
player6
player7
player8
player9
player10

就是这样。感谢您的帮助:))

2 个答案:

答案 0 :(得分:0)

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)

答案 1 :(得分:0)

我会存储字典,然后打印出所有播放器。

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)