python通过反转字符串来检查重复项

时间:2015-10-15 20:30:28

标签: python dictionary

我有一个带有以下形式的密钥的字典:

d['a:b']
d['c:d']
d['e:f']
d['d:c']
d['b:a']
d['f:e']

如何检查并删除重复项,其中重复项为

d['a:b'] = d['b:a']

所以在检查和删除后,字典将由

组成
d['a:b']
d['c:d']
d['e:f']

3 个答案:

答案 0 :(得分:1)

d.keys()返回一个副本,因此可以弹出项目。

d = { k:None for k in  ('a:b','c:d','e:f','d:c','b:a','f:e') }
for k in d.keys():
    if '{}:{}'.format(k[2],k[0]) in d:
        d.pop(k)

答案 1 :(得分:0)

unique = []
delete = []
for key in d.keys():
  if key[::-1] in unique:
    delete.append(key)
  else:
    unique.append(key)
for key in delete: del d[key]

两个循环不是很好,但有效

答案 2 :(得分:-1)

unique = []
for key in sorted(d.keys()):
    if key in unique or key[-1] + key[1] + key[0] in unique:
        d.pop(key)
    unique.append(key)
print d