Python使用嵌套for循环处理soccer_match数据集的两个实操问题
问题1:合并队服颜色为一维列表
你当前的代码是直接把每支球队的颜色子列表整体添加到总列表中,只需要再加一层循环遍历子列表的单个颜色逐个添加即可,不需要用到列表推导式或额外函数:
colors = [] for team in soccer_match: # 遍历当前球队的每一种队服颜色 for color in team['colors']: colors.append(color) print(colors)
运行后得到的输出为:['blue', 'white', 'red', 'green', 'gold']
问题2:提取各队队长列表
用两层嵌套for循环即可实现,外层遍历所有球队,内层遍历单支球队的所有球员,判断captain属性为True时就把对应球员信息添加到结果列表:
captains = [] for team in soccer_match: # 遍历当前球队的所有球员 for player in team['players']: if player['captain']: captains.append(player) print(captains)
如果你只需要提取队长的姓名,把append的内容改为player['name']即可,输出结果为:['Hugo LLORIS', 'Mile JEDINAK']
内容的提问来源于stack exchange,提问作者imkusoh
相关产品推荐
相关产品推荐

