For循环输出所有相同的值

2024-05-23 15:09:55 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我有一个json列表,并使用两个输入request.args.get('sport')和request.args.get('team')在列表中查找这些值。如果找到该值,我希望输出有关球队和运动的更多信息

这就是我试图做的:

for a_team in scores_list['scores']:
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list = []
        for a_team['team'] in scores_list['scores']:
            teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                      a_team['sport'], a_team['home_name'],
                                                                      a_team['home_score'], a_team['away_score'],
                                                                      a_team['away_name']))

问题是,这种方法在不同的时间输出相同的值集。我想从request.args.get('team')输出团队的所有不同游戏。 我是python新手,我搜索了所有人,但找不到答案

下面是我的json文件示例:

 {
  "scores": [
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "15-2020",
      "boxscore": "202012190gnb",
      "away_name": "Carolina Panthers",
      "away_abbr": "car",
      "away_score": 16,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 24,
      "winning_name": "Green Bay Packers",
      "winning_abbr": "gnb",
      "losing_name": "Carolina Panthers",
      "losing_abbr": "car"
    },
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "19-2020",
      "boxscore": "202101160gnb",
      "away_name": "Los Angeles Rams",
      "away_abbr": "ram",
      "away_score": 18,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 32,
      "winning_name": "Green Bay Packers",
      "winning_abbr": "gnb",
      "losing_name": "Los Angeles Rams",
      "losing_abbr": "ram"
    },
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "20-2020",
      "boxscore": "202101240gnb",
      "away_name": "Tampa Bay Buccaneers",
      "away_abbr": "tam",
      "away_score": 31,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 26,
      "winning_name": "Tampa Bay Buccaneers",
      "winning_abbr": "tam",
      "losing_name": "Green Bay Packers",
      "losing_abbr": "gnb"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "16-2020",
      "boxscore": "202012270kan",
      "away_name": "Atlanta Falcons",
      "away_abbr": "atl",
      "away_score": 14,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 17,
      "winning_name": "Kansas City Chiefs",
      "winning_abbr": "kan",
      "losing_name": "Atlanta Falcons",
      "losing_abbr": "atl"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "17-2020",
      "boxscore": "202101030kan",
      "away_name": "Los Angeles Chargers",
      "away_abbr": "sdg",
      "away_score": 38,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 21,
      "winning_name": "Los Angeles Chargers",
      "winning_abbr": "sdg",
      "losing_name": "Kansas City Chiefs",
      "losing_abbr": "kan"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "19-2020",
      "boxscore": "202101170kan",
      "away_name": "Cleveland Browns",
      "away_abbr": "cle",
      "away_score": 17,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 22,
      "winning_name": "Kansas City Chiefs",
      "winning_abbr": "kan",
      "losing_name": "Cleveland Browns",
      "losing_abbr": "cle"
    },
    {
      "sport": "football",
      "team": "chiefs",
      "full_name": "Kansas City Chiefs",
      "week": "19-2020",
      "boxscore": "202101240kan",
      "away_name": "Buffalo Bills",
      "away_abbr": "buf",
      "away_score": 24,
      "home_name": "Kansas City Chiefs",
      "home_abbr": "kan",
      "home_score": 38,
      "winning_name": "Kansas City Chiefs",
      "winning_abbr": "kan",
      "losing_name": "Buffalo Bills",
      "losing_abbr": "buf"
    },
    {
      "sport": "football",
      "team": "buccaneers",
      "full_name": "Tampa Bay Buccaneers",
      "week": "21-2020",
      "boxscore": "202102070tam",
      "away_name": "Kansas City Chiefs",
      "away_abbr": "kan",
      "away_score": 9,
      "home_name": "Tampa Bay Buccaneers",
      "home_abbr": "tam",
      "home_score": 31,
      "winning_name": "Tampa Bay Buccaneers",
      "winning_abbr": "tam",
      "losing_name": "Kansas City Chiefs",
      "losing_abbr": "kan"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "7-23-2020",
      "boxscore": "LAN/LAN202007230",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 8,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "San Francisco Giants",
      "losing_abbr": "SFG"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "7-24-2020",
      "boxscore": "LAN/LAN202007240",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 9,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "San Francisco Giants",
      "losing_abbr": "SFG"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "7-25-2020",
      "boxscore": "LAN/LAN202007250",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 5,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 4,
      "winning_name": "San Francisco Giants",
      "winning_abbr": "SFG",
      "losing_name": "Los Angeles Dodgers",
      "losing_abbr": "LAD"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "8-5-2020",
      "boxscore": "COL/COL202008050",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 4,
      "home_name": "Colorado Rockies",
      "home_abbr": "COL",
      "home_score": 3,
      "winning_name": "San Francisco Giants",
      "winning_abbr": "SFG",
      "losing_name": "Colorado Rockies",
      "losing_abbr": "COL"
    },
    {
      "sport": "baseball",
      "team": "giants",
      "full_name": "San Francisco Giants",
      "date": "8-6-2020",
      "boxscore": "COL/COL202008060",
      "away_name": "San Francisco Giants",
      "away_abbr": "SFG",
      "away_score": 4,
      "home_name": "Colorado Rockies",
      "home_abbr": "COL",
      "home_score": 6,
      "winning_name": "Colorado Rockies",
      "winning_abbr": "COL",
      "losing_name": "San Francisco Giants",
      "losing_abbr": "SFG"
    },
    {
      "sport": "baseball",
      "team": "rays",
      "full_name": "Tampa Bay Rays",
      "date": "10-27-2020",
      "boxscore": "LAN/LAN202010270",
      "away_name": "Tampa Bay Rays",
      "away_abbr": "TBR",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 3,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "Tampa Bay Rays",
      "losing_abbr": "TBR"
    }
  ]
}

Tags: namehometeamfullscoresanabbrbay
3条回答
  1. 也许您不应该在每次迭代中清除团队列表:
for i in range(3):
    # Here you'll bind a new empty 
    # list to the variable `result`
    # each time this line executed
    results = [i]
print(results)
# [2]

相反,请在循环之外创建一个列表,并在迭代期间附加新值:

results = []  # List created before entering the loop
for i in seq:
    results.append(i)  # And new values appended to the same list
print(results)
# [0, 1, 2]

  1. 当您使用dict查找作为循环变量时,您清楚地了解发生了什么吗
d = {'a': 1}
for d['a'] in range(10):
    pass
print(d)
# {'a': 9}

这字面意思是:

  • 从iterable(sequence)获取下一项
  • 并通过'a'键将此项置于dictd

为了使代码更可预测,请在for循环中定义所需的新变量

d = {'a': 0}
for a in range(3):
    d['a'] = d['a'] + a
print(d)
# {'a': 3}

我的答案将只包括scores_list中表示json数据文件的两个条目,但是代码应该会让您重新开始。我将使用列表理解(主要是因为我喜欢它们)。从技术上讲game_info()的方法细节可以在理解中处理,但我认为这并不能真正增加清晰度

import json # for printing in demo

## -----------------------
# this just makes our comprehension easier to follow later in the code.
## -----------------------
def game_info(game):
    return "{} ({}) ({}) {} ({}) - ({}) {}".format(
        game['full_name'],
        game['date'],
        game['sport'],
        game['home_name'],
        game['home_score'],
        game['away_score'],
        game['away_name']
    )
## -----------------------

scores_list = {
  "scores": [
    {
      "sport": "football",
      "team": "packers",
      "full_name": "Green Bay Packers",
      "week": "15-2020",
      "boxscore": "202012190gnb",
      "away_name": "Carolina Panthers",
      "away_abbr": "car",
      "away_score": 16,
      "home_name": "Green Bay Packers",
      "home_abbr": "gnb",
      "home_score": 24,
      "winning_name": "Green Bay Packers",
      "winning_abbr": "gnb",
      "losing_name": "Carolina Panthers",
      "losing_abbr": "car"
    },
    ## rows removed for clarity....
    {
      "sport": "baseball",
      "team": "rays",
      "full_name": "Tampa Bay Rays",
      "date": "10-27-2020",
      "boxscore": "LAN/LAN202010270",
      "away_name": "Tampa Bay Rays",
      "away_abbr": "TBR",
      "away_score": 1,
      "home_name": "Los Angeles Dodgers",
      "home_abbr": "LAD",
      "home_score": 3,
      "winning_name": "Los Angeles Dodgers",
      "winning_abbr": "LAD",
      "losing_name": "Tampa Bay Rays",
      "losing_abbr": "TBR"
    }
  ]
}

#requested_sport = request.args.get('sport').lower()
requested_sport = "baseball"

#requested_team = request.args.get('team').lower()
requested_team = "rays"

## -----------------------
# find all the games where we have a match on both sport and team name.
## -----------------------
interesting_games = [
    game_info(game) for game in scores_list['scores']
    if game["sport"] == requested_sport and game["team"] == requested_team
]
## -----------------------

print(json.dumps(interesting_games, indent=2))

这应该给你:

[
  "Tampa Bay Rays (10-27-2020) (baseball) Los Angeles Dodgers (3) - (1) Tampa Bay Rays"
]

如果您不想使用方法调用,那么理解可能更像:

interesting_games = [
    "{} ({}) ({}) {} ({}) - ({}) {}".format(
        game['full_name'],
        game['date'],
        game['sport'],
        game['home_name'],
        game['home_score'],
        game['away_score'],
        game['away_name']
    )
    for game in scores_list['scores']
    if game["sport"] == requested_sport and game["team"] == requested_team
]
        for team in scores_list['scores']:
            teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(team['full_name'], team['date'],
                                                                      team['sport'], team['home_name'],
                                                                      team['home_score'], team['away_score'],
                                                                      team['away_name']))

您正在源代码中的两个位置对scores_list['scores']进行迭代:

for a_team in scores_list['scores']:
            # ^^^^^^^^^^^^^^^^^^^^^ here
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list = []
        for a_team['team'] in scores_list['scores']:
                            # ^^^^^^^^^^^^^^^^^^^^^ and here
            teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                      a_team['sport'], a_team['home_name'],
                                                                      a_team['home_score'], a_team['away_score'],
                                                                      a_team['away_name']))

这可能不是你想要的。当if为真时,您手中已经有一个a_team您感兴趣 在中,您可以直接使用它:

for a_team in scores_list['scores']:
    if a_team['sport'].lower() == request.args.get('sport').lower() \
            and a_team['team'].lower() == request.args.get('team').lower():
        teams_list = []
        teams_list.append("{} ({}) ({}) {} ({}) - ({}) {}".format(a_team['full_name'], a_team['date'],
                                                                  a_team['sport'], a_team['home_name'],
                                                                  a_team['home_score'], a_team['away_score'],
                                                                  a_team['away_name']))

现在你只需要找出你想把teams_list = []放在哪里。可能在for循环开始之前

相关问题 更多 >