我正在嘗試從以下結構中洗掉重復項:
data = [
{
'author': 'Isav Tuco',
'authorId': 62,
'tags': ['fire', 'works']
},
{
'author': 'Sham Isa',
'authorId': 23,
'tags': ['badminton', 'game']
},
{
'author': 'Isav Tuco',
'authorId': 62,
'tags': ['fire', 'works']
}
]
我已經嘗試過這里可用的以下方法。從字典串列中洗掉重復項的代碼:
seen = set()
new_list = []
for d in data:
t = tuple(d.items())
if d not in seen:
seen.add(d)
new_list.append(d)
uj5u.com熱心網友回復:
在 Python 中洗掉重復串列中的重復字典的解決方案并不完全適用,因為您有內部串列。
您還需要對它們進行元組化以便在集合中使用。
一種方法是:
data = [{'author': 'Isav Tuco',
'authorId': 62,
'tags': ['fire', 'works']},
{'author': 'Sham Isa',
'authorId': 23,
'tags': ['badminton', 'game']},
{'author': 'Isav Tuco',
'authorId': 62,
'tags': ['fire', 'works']}]
seen = set()
new_list = []
for d in data:
l = []
# use sorted items to avoid {"a":1, "b":2} != {"b":2, "a":1} being
# different when getting the dicts items
for (a,b) in sorted(d.items()):
if isinstance(b,list):
l.append((a,tuple(b))) # convert lists to tuples
else:
l.append((a,b))
# convert list to tuples so you can put it into a set
t = tuple(l)
if t not in seen:
seen.add(t) # add the modified value
new_list.append(d) # add the original value
print(new_list)
輸出:
[{'author': 'Isav Tuco', 'authorId': 62, 'tags': ['fire', 'works']},
{'author': 'Sham Isa', 'authorId': 23, 'tags': ['badminton', 'game']}]
雖然這是被黑了 - 你可能想要獲得自己更好的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/447812.html
