python-3.x 如何通过id列表过滤对象列表?

xu3bshqb  于 2023-07-01  发布在  Python
关注(0)|答案(5)|浏览(133)

假设我们有一个这样的对象列表:

my_objects = [
    {
        "id":0,
        "some_value":"a"
    },
    {
        "id":1,
        "some_value":"a"
    },
    {
        "id":2,
        "some_value":"b"
    },
    {
        "id":3,
        "some_value":"b"
    },
]

给定一个像这样的id列表:

ids = [1, 2]

用pythonic的方法来检索列表中所有id的对象的列表是什么?例如:

my_objects_filtered = [
    {
        "id":1,
        "some_value":"a"
    },
    {
        "id":2,
        "some_value":"b"
    }
]

最后我想要的是列表“ids”中所有id的“some_value”值的列表:

ids = [a, b]

我可以这样做:

some_values = [my_object.param_id for my_object in my_objects_filtered]

但我不知道如何得到my_objects_filtered提前感谢。

js5cn81o

js5cn81o1#

类似下面的东西

my_objects = [
    {
        "id": 0,
        "some_value": "a"
    },
    {
        "id": 1,
        "some_value": "a"
    },
    {
        "id": 2,
        "some_value": "b"
    },
    {
        "id": 3,
        "some_value": "b"
    },
]
ids = [1, 2]
final_list = [x['some_value'] for x in my_objects if x['id'] in ids]
print(final_list)

输出

['a', 'b']
wnrlj8wa

wnrlj8wa2#

有一个简洁的可选if部件列表解析:

[obj["some_value"] for obj in my_objects if obj["id"] in ids]
rxztt3cl

rxztt3cl3#

ids = [x.get("some_value") for x in my_objects if x['id'] in ids]

#print(ids)
['a', 'b']
a64a0gku

a64a0gku4#

你可以尝试这样的东西:

my_objects = [
    {
        "id":0,
        "some_value":"a"
    },
    {
        "id":1,
        "some_value":"a"
    },
    {
        "id":2,
        "some_value":"b"
    },
    {
        "id":3,
        "some_value":"b"
    },
]
id_to_select = [1 ,2]
my_objects_filtered = [obj["some_value"] for obj in my_objects if obj["id"] in id_to_select]
print(my_objects_filtered) 
# [{'id': 1, 'some_value': 'a'}, {'id': 2, 'some_value': 'b'}]

但我不确定是不是pythonic的方式
使用filter和lambda可能更好:

my_objects = [
    {
        "id":0,
        "some_value":"a"
    },
    {
        "id":1,
        "some_value":"a"
    },
    {
        "id":2,
        "some_value":"b"
    },
    {
        "id":3,
        "some_value":"b"
    },
]
id_to_select = [1 ,2]
my_objects_filtered = list(map(lambda obj: obj["some_value"],filter(lambda obj: obj["id"] in id_to_select, my_objects)))
print(my_objects_filtered)
# ['a', 'b']
bxfogqkk

bxfogqkk5#

如果你知道idsome_value会出现在每个字典中,那么你可以使用operator.itemgetter

from operator import itemgetter

get_id_val = itemgetter("id", "some_value")

result = [val for i, val in map(get_id_val, my_objects) if i in ids]

如果你也知道它们是有序的,并且字典只有2个键,那么你可以只Mapdict.values

[val for i, val in map(dict.values, my_objects) if i in ids]

如果它们是有序的,但可能有更多的键,那么只需抛出一个catch all变量:

[val for i, val, *_ in map(dict.values, my_objects) if i in ids]

相关问题