2 回答

TA貢獻1827條經驗 獲得超9個贊
嘗試這個:
res = [{**x, **y} for y in players for x in squad if x['id'] == y['id']] d = [dict(sorted(d.items())) for d in res]
輸出:
[{'age': '19 years 275 days', 'birth': '24 July 2000', 'birth_exact': 964396800000.0, 'country': 'Ecuador', 'first': 'Leonardo', 'id': 74562.0, 'isoCode': 'EC', 'last': 'Campana', 'loan': False, 'name': 'Leonardo Campana', 'nationalTeam': 'Ecuador', 'playerId': 179304.0, 'position': 'F', 'positionInfo': 'Centre Striker', 'season': 2019, 'shirtNum': None, 'team': 'Wolverhampton Wanderers', 'team_id': 38, 'team_shortName': 'Wolves'}, {'age': '24 years 186 days', 'birth': '21 October 1995', 'birth_exact': 814233600000.0, 'country': 'Portugal', 'first': 'Daniel', 'id': 11362.0, 'isoCode': 'PT', 'last': 'Castelo Podence', 'loan': False, 'name': 'Daniel Podence', 'nationalTeam': 'Portugal', 'playerId': 180050.0, 'position': 'M', 'positionInfo': 'Left/Right Winger', 'season': 2019, 'shirtNum': 10.0, 'team': 'Arsenal', 'team_id': 1, 'team_shortName': 'Arsenal'}]

TA貢獻2012條經驗 獲得超12個贊
我刪除了您的一些數據以減少輸出 - 您可以使用 2 個字典來快速訪問列表中的 id(小隊與球員)。
如果他們有一個具有相同密鑰的小隊,您循環一次并更新他們 - 您還可以使用 dicts 斷言所有小隊是否有球員信息:
players = [ {'age': '19 years 275 days',
'birth': '24 July 2000',
'id': 74562.0 },
{'age': '24 years 186 days',
'birth': '21 October 1995',
'birth_exact': 814233600000.0,
'id': 11362.0,},
{'age': '24 years 186 days',
'birth': '21 October 1995',
'birth_exact': 814233600000.0,
'id':42,}]
# fixed name
squads = [ {'id': 11362.0,
'team': 'Arsenal',
'team_id':1,
'team_shortName': 'Arsenal'},
{'id': 74562.0,
'team': 'Wolverhampton Wanderers',
'team_id': 38,
'team_shortName': 'Wolves'},
{'id': -3,
'team': 'Wolverhampton Wanderers',
'team_id': 38,
'team_shortName': 'Wolves'}]
p_sort = sorted(players, key=lambda k: k['id'])
s_sort = sorted(squads, key=lambda k: k['id'])
keyed_players = {a["id"]:a for a in p_sort} # easier access for IN - check
keyed_squads = {a["id"]:a for a in s_sort} # easier access for IN - check
# iterate players and modify them if squad info given, else printout info
for player in p_sort:
if player["id"] in keyed_squads:
player.update(keyed_squads[player["id"]])
else:
print("player", player["id"], "has no squad info")
print(p_sort)
# get squads without players
for s in keyed_squads:
if s not in keyed_players:
print("squad", s, "has no player info")
輸出:
player 42 has no squad info
[{'age': '24 years 186 days', 'birth': '21 October 1995',
'birth_exact': 814233600000.0, 'id': 42},
{'age': '24 years 186 days', 'birth': '21 October 1995',
'birth_exact': 814233600000.0, 'id': 11362.0,
'team': 'Arsenal', 'team_id': 1, 'team_shortName': 'Arsenal'},
{'age': '19 years 275 days', 'birth': '24 July 2000', 'id': 74562.0,
'team': 'Wolverhampton Wanderers', 'team_id': 38, 'team_shortName': 'Wolves'}]
squad -3 has no player info
該代碼肯定比您的代碼包含更多行 - 但它更清楚什么做什么 - 如果您在 4 周內查看它,這可能是一個獎勵。
添加回答
舉報