<p><em>我假设在<code>a_list</code>中,一个嵌套的<code>list</code>将具有相同的<code>'id'</code>,并且每个id只有一个列表。</em></p>
<p>为了实现这一点,迭代b_列表并检查<code>a_list</code>中的匹配。如果匹配,则向<code>a_list</code>的dict对象添加值</p>
<pre><code>>>> a_list=[
... [{'id':'123', 'user':'Foo'}, {'id':'123','user':'Jonny'}],
... [{'id':'456', 'user':'Bar'}, {'id':'456','user':'Mary'}],
... ]
>>> b_list=[{'post':'123','text': 'Something'}, {'post':'456', 'text': 'Another thing'}]
>>>
>>> for dict_item in b_list:
... id = dict_item['post']
... for list_item in a_list:
... if list_item[0]['id'] == id:
... dict_item['comments'] = list_item
... break
...
>>> b_list
[{
'text': 'Something',
'post': '123',
'comments': [
{
'id': '123',
'user': 'Foo'
},
{
'id': '123',
'user': 'Jonny'
}
]
},
{
'post': '456',
'text': 'Another thing',
'comments': [
{
'id': '456',
'user': 'Bar'
},
{
'id': '456',
'user': 'Mary'
}
]
}
]
</code></pre>