我有以下形式鍵的字典:蟒蛇重複檢查通過反轉字符串
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']
我有以下形式鍵的字典:蟒蛇重複檢查通過反轉字符串
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']
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)
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]
不是很好用兩個迴路,但工程
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
只是爲了澄清,'D'是你的字典嗎? –
@RNar是的,d是字典 – GISUser9