基于匹配的两个键创建新列表

2024-06-25 23:17:57 发布

您现在位置: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()

Tags: namehttpsapiurll1列表字典co
1条回答
网友
1楼 · 发布于 2024-06-25 23:17:57

您可以使用列表理解:

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']}]

相关问题 更多 >