我有一个名为results
的字典。
字典的结构如下:
{'a': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']]}
我希望删除每个键的重复嵌套列表,因此将字典保留为:
{'a': [['1', '2', '4'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2']]}
我已经尝试过:
newdict = {}
for k, v in results.items():
for i in v:
if i not in i:
newdict[k] = i
有什么帮助吗?提前致谢!
最佳答案
您的代码是错误的,无法修复(抱歉),主要是因为这两行:
if i not in i: # makes no sense testing if something is inside itself
newdict[k] = i # overwrites the key with one list
您必须对每个列表进行计数,并且仅保留每个列表出现的一次。
如果顺序并不重要,您可以使用嵌套的字典/集合/列表理解来做到这一点。
results = {'a': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']], 'b': [['2', '2', '4'],['2', '2', '2'],['1', '2', '4']], 'c': [['1', '2', '4'],['1', '2', '2'],['1', '2', '2']]}
newdict = {k:[list(y) for y in {tuple(x) for x in v}] for k,v in results.items()}
print(newdict)
结果:
{'a': [['1', '2', '2'], ['1', '2', '4']], 'b': [['2', '2', '4'], ['1', '2', '4'], ['2', '2', '2']], 'c': [['1', '2', '2'], ['1', '2', '4']]}
使用set
可以保持唯一性,但不能将list
放入set
中,因此表达式转换为首先元组
(可散列),并在处理完成后转换回列表
。
关于Python-删除字典中的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49587431/