python - 根据匹配两个键创建新列表
问题描述
给定以 x 字典为元素的 y 列表,我想生成一个新列表,其中包含一组连接的字典。每个字典都保证有一个名为“homeworld”的键和一个名为“name”的键,但除此之外还可以有任意一组键。例如,想象以下两个列表:
list1 = [{"name": "Leia Organa", "homeworld": "https://swapi.co/api/planets/2/"},
{"name": "C-3PO", "homeworld": "https://swapi.co/api/planets/1/"},
{"name": "Bail Prestor Organa", "homeworld": "https://swapi.co/api/planets/2/"},
{"name": "Luke Skywalker", "homeworld": "https://swapi.co/api/planets/1/"}]
list2 = [{"name": "Alderaan", "url": "https://swapi.co/api/planets/2/"},
{"name": "Yavin IV", "url": "https://swapi.co/api/planets/3/"},
{"name": "Tatooine", "url": "https://swapi.co/api/planets/1/"}]
基于键 list1['homeworld'] 和 list2['url'],我想生成一个连接列表:
list3 = [
{"name": "Alderaan", "persons": ["Leia Organa", "Bail Prestor Organa"]},
{"name": "Tatooine", "persons": ["Luke Skywalker", "C-3PO"]}
]
在 Python 中执行此操作的最佳方法是什么?
到目前为止我尝试过的...
from collections import defaultdict
l1 = get_planets()['results']
l2 = get_people()['results']
d = defaultdict(dict)
for l in (l1, l2): <-----is this even set up correctly?
for elem in l:
# how to write this here? if l2['homeworld'] == l1['url']: ???
d[elem['name']].update(elem) <---not sure what goes here
l3 = d.values()
解决方案
您可以使用列表理解:
list1 = [{"name": "Leia Organa", "homeworld": "https://swapi.co/api/planets/2/"},
{"name": "C-3PO", "homeworld": "https://swapi.co/api/planets/1/"},
{"name": "Bail Prestor Organa", "homeworld": "https://swapi.co/api/planets/2/"},
{"name": "Luke Skywalker", "homeworld": "https://swapi.co/api/planets/1/"}]
list2 = [{"name": "Alderaan", "url": "https://swapi.co/api/planets/2/"},
{"name": "Yavin IV", "url": "https://swapi.co/api/planets/3/"},
{"name": "Tatooine", "url": "https://swapi.co/api/planets/1/"}]
list3 = [{'name': x['name'], 'persons': [y['name'] for y in list1 if y['homeworld'] == x['url']]} for x in list2]
list3 = [x for x in list3 if x['persons']]
print(list3)
# [{'name': 'Alderaan', 'persons': ['Leia Organa', 'Bail Prestor Organa']},
# {'name': 'Tatooine', 'persons': ['C-3PO', 'Luke Skywalker']}]
推荐阅读
- java - 未能执行目标 org.apache.maven.plugins:maven-compiler-plugin:3.8.1
- python - Python text out of TD error 'NoneType' object has no attribute 'text' 为什么?
- amazon-iam - 从命令行获取 AWS 访问密钥
- mysql - 按日期排序后如何按名称使用 ORDER?
- websocket - Deno:如何将 WebSocket 与橡木一起使用?
- javascript - 无法使用 onChangeText 更新反应原生组件中的状态
- angular - 提交后重置ngForm在Angular 9中不起作用
- bash - bash 无法将多个数字条件与 bc 进行比较
- excel - 更改时将单元格复制到另一列
- c# - 有没有办法使用 c# 从 Minecraft 统一重新创建班次系统