过滤Python中的列表

时间:2012-11-07 03:46:36

标签: python python-3.x

词典来源列表

[
    {'main_id': 0, '_id': ObjectId('111111111111111'), 'key1': 'val1'}, 
    {'main_id': 1, '_id': ObjectId('222222222222222'), 'key1': 'val2'}, 
    {'main_id': 1, '_id': ObjectId('333333333333333'), 'key1': 'val3'}, 
    {'main_id': 4, '_id': ObjectId('444444444444444'), 'key1': 'val4'},
    {'main_id': 2, '_id': ObjectId('555555555555555'), 'key1': 'val5'},
]

过滤词典列表

[
    {'main_id': 0, '_id': ObjectId('111111111111111'), 'key1': 'val1'}, 
    {'main_id': 1, '_id': ObjectId('222222222222222'), 'key1': 'val2'}, 
    {'main_id': 2, '_id': ObjectId('555555555555555'), 'key1': 'val3'},
]

我想获得一个新的词典列表:

[
    {'main_id': 1, '_id': ObjectId('333333333333333'), 'key1': 'val3'}, 
    {'main_id': 4, '_id': ObjectId('444444444444444'), 'key1': 'val4'},
]

换句话说,我想要一个新列表来包含过滤列表中不存在的值。 你的想法?

3 个答案:

答案 0 :(得分:2)

一个班轮:

result = [s for s in original if s not in filtered]

或使用filter

filter(lambda x: x not in filtered, original)

答案 1 :(得分:1)

full = [
    {'main_id': 0, '_id': ObjectId('111111111111111'), 'key1': 'val1'}, 
    {'main_id': 1, '_id': ObjectId('222222222222222'), 'key1': 'val2'}, 
    {'main_id': 1, '_id': ObjectId('333333333333333'), 'key1': 'val3'}, 
    {'main_id': 4, '_id': ObjectId('444444444444444'), 'key1': 'val4'},
    {'main_id': 2, '_id': ObjectId('555555555555555'), 'key1': 'val5'},
]
filtered = [
    {'main_id': 0, '_id': ObjectId('111111111111111'), 'key1': 'val6'}, 
    {'main_id': 1, '_id': ObjectId('222222222222222'), 'key1': 'val7'}, 
    {'main_id': 2, '_id': ObjectId('555555555555555'), 'key1': 'val8'},
]

diff = [x for x in full if x not in filtered]

答案 2 :(得分:0)

使用原始数据:

# dummy!
ObjectId = str


original = [
    {'main_id': 0, '_id': ObjectId('111111111111111'), 'key1': 'val1'}, 
    {'main_id': 1, '_id': ObjectId('222222222222222'), 'key1': 'val2'}, 
    {'main_id': 1, '_id': ObjectId('333333333333333'), 'key1': 'val3'}, 
    {'main_id': 4, '_id': ObjectId('444444444444444'), 'key1': 'val4'},
    {'main_id': 2, '_id': ObjectId('555555555555555'), 'key1': 'val5'},
]

filtered = [
    {'main_id': 0, '_id': ObjectId('111111111111111'), 'key1': 'val1'}, 
    {'main_id': 1, '_id': ObjectId('222222222222222'), 'key1': 'val2'}, 
    {'main_id': 2, '_id': ObjectId('555555555555555'), 'key1': 'val3'},
]

new_list = [d for d in original if d not in filtered]

print(new_list)