我需要像这样删除字典中重复的元素:
{
1: ['1', '2', '3'],
2: ['4', '3', '6', '7'],
3: ['8', '1', '9']
}
使最终结果如下
{
1: ['1', '2', '3'],
2: ['4', '6', '7'],
3: ['8', '9']
}
请告诉我怎么做,我不知道
假设d
是输入,您可以使用一个集合来跟踪所看到的值。这里使用字典理解和"作弊"添加值:
seen = set()
out = {k: [x for x in v
if x not in seen and not seen.add(x)]
for k,v in d.items()}
输出:
{1: ['1', '2', '3'],
2: ['4', '6', '7'],
3: ['8', '9']}
与经典循环相同:
out = {}
seen = set()
for k,v in d.items():
l = []
for x in v:
if x not in seen:
seen.add(x)
l.append(x)
out[k] = l
重复相同的旧的see -set解决方案是无聊的:-P。让我们来玩一下计数器:
from collections import Counter
d = {
1: ['1', '2', '3'],
2: ['4', '3', '6', '7'],
3: ['8', '1', '9']
}
seen = Counter()
for a in d.values():
uniq = Counter(dict.fromkeys(a, 1))
a[:] = uniq - seen
seen |= uniq
print(d)
每个列表首先使用字典对其自身进行重复数据删除。然后变成一个计数器,这样我们就可以方便地减去之前看到的值。把新的写进列表,并把它们添加到已看到的列表中。
上网试试!
对于集并运算符和差运算符也可以这样做。因为集合是无序的,所以最终的列表需要排序。再次假设d是原始字典。
s = set()
for k in d:
z = d[k]
d[k]= sorted(list(set(z).difference(s)))
s |= set(z)