简体   繁体   中英

Iterating through a list and querying a value

Suppose you have a list of teams keys name and type as shown below

teams = [

    {"Name": "Manchester",
     "Type": "Soccer"
     },
    {
        "Name": "Chelsea",
        "Type": "Soccer"
    },
    {
        "Name": "Lakers",
        "Type": "Basketball"
    }
]

teamStr = ""

#iterate through the list and concatenate to teamStr the team whose type is Soccer 
for index in teams:
    for value in teams[index].items:
        if value == "Soccer":
            teamStr += value

If say you wanted to iterate through the list and get the names of Soccer teams only. For example I want to get Chelsea and Manchester as output, In a nutshell I'd like to iterate through the list and concatenate to teamStr the team whose type is Soccer, such that the final teamStr = "Manchester, Chelsea"

Try this:

soccerTeams = [team['Name'] for team in teams if team['Type'] == 'Soccer']
print(soccerTeams)
# ['Manchester', 'Chelsea']
teamStr = ', '.join(soccerTeams)
print(teamStr)
# Manchester, Chelsea

You can iterate through the list by calling Type keys in every iteration

for i in range(len(teams)):
    if teams[i]['Types'] == 'Soccer':
        teamStr += teams[i]['Name']

I haven't put spaces between team names, but if you want that:

for i in range(len(teams)):
    if teams[i]['Types'] == 'Soccer':
        teamStr += teams[i]['Name'] + ' '
    teamStr.rstrip(' ') #To remove the unwanted whitespace at the end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM