<p>这个<a href="https://stackoverflow.com/a/8714242/5741205">answer</a>将有助于解决一个更一般的问题-找到唯一的元素不是通过单个属性(在您的例子中是<code>id</code>),而是如果任何一个</strong>嵌套属性不同</p>
<p>下面的代码将返回唯一元素的索引列表</p>
<pre><code>import copy
def make_hash(o):
"""
Makes a hash from a dictionary, list, tuple or set to any level, that contains
only other hashable types (including any lists, tuples, sets, and
dictionaries).
"""
if isinstance(o, (set, tuple, list)):
return tuple([make_hash(e) for e in o])
elif not isinstance(o, dict):
return hash(o)
new_o = copy.deepcopy(o)
for k, v in new_o.items():
new_o[k] = make_hash(v)
return hash(tuple(frozenset(sorted(new_o.items()))))
l = [
{
"type": "users",
"attributes": {
"first-name": "John",
"email": "john.smith@gmail.com",
"last-name": "Smith",
"handle": "jsmith"
},
"id": "1234"
},
{
"type": "users",
"attributes": {
"first-name": "AAA",
"email": "aaa.aaah@gmail.com",
"last-name": "XXX",
"handle": "jsmith"
},
"id": "1234"
},
{
"type": "users",
"attributes": {
"first-name": "John",
"email": "john.smith@gmail.com",
"last-name": "Smith",
"handle": "jsmith"
},
"id": "1234"
},
]
# get indicies of unique elements
In [254]: list({make_hash(x):i for i,x in enumerate(l)}.values())
Out[254]: [1, 2]
</code></pre>