import re
s = {'Alice':'P-1', 12:'F-1', 17:'P-1', 'Bob':'F-1', 19:'T'}
removal_count = len([b for a, b in s.items() if b[-1].isdigit() and [re.findall('\d+$', c) for c in s.values()].count(re.findall('\d+$', b)) > 1])
print(removal_count)
输出:
4
要筛选词典:
new_s = {a:b for a, b in s.items() if [re.findall('\d+$', c) for c in s.values()].count(re.findall('\d+$', b)) <= 1}
>>> import collections
>>> def remove_duplicates(d):
... grouper = collections.defaultdict(list)
... for k, v in d.items():
... grouper[v].append(k)
... total = 0
... for val, keys in grouper.items():
... if len(keys) > 1:
... for k in keys:
... del d[k]
... total += len(keys)
... return total
...
>>> d = {'Alice':'P-1', 12:'F-1', 17:'P-1', 'Bob':'F-1', 19:'T'}
>>> remove_duplicates(d)
4
>>> d
{19: 'T'}
你可以试试这个:
输出:
要筛选词典:
输出:
下面是一个函数,它可以满足您的需要:
它在线性时间内工作,但需要线性空间。就我个人而言,我会创建一个新的字典,而不是修改原来的,但这就是上面所做的。你知道吗
相关问题 更多 >
编程相关推荐