我有2个数组,如下所示:
数组1:
[
{"name": "A", "class" : "1"},
{"name": "B", "class" : "2"},
{"name": "C", "class" : "3"}
]
数组2:
[ "A","B"]
我想合并2个数组,我的预期结果是:
[
{"name": "A", "class" : "1"},
{"name": "B", "class" : "2"}
]
任何建议都值得赞赏
到目前为止我发现了什么:
答案 0 :(得分:5)
只需使用list
理解:
first = [
{"name": "A", "class" : "1"},
{"name": "B", "class" : "2"},
{"name": "C", "class" : "3"}
]
second = ['A', 'B']
result = [d for d in first if d['name'] in second]
print(result)
输出:
[{'name': 'A', 'class': '1'}, {'name': 'B', 'class': '2'}]
在评论中提出的情况:
from operator import itemgetter
first = [
{"name": "A", "class" : "1"},
{"name": "B", "class" : "2"},
{"name": "C", "class" : "3"}
]
second = [
{"name": "A"},
{"name": "B"}
]
result = [d for d in first if d['name'] in map(itemgetter('name'), second)]
print(result)
输出:
[{'name': 'A', 'class': '1'}, {'name': 'B', 'class': '2'}]