我有一个嵌套列表(列表的列表),我想删除重复,但我得到一个错误。这是一个例子:从python嵌套列表中获取唯一值
images = [
[
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "marine-transportation-transports-maritimes.xml"
},
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "railway-transportation-transports-ferroviaires.xml"
}
],
[
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "marine-transportation-transports-maritimes.xml"
},
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "railway-transportation-transports-ferroviaires.xml"
}
],
[
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "marine-transportation-transports-maritimes.xml"
},
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "railway-transportation-transports-ferroviaires.xml"
}
]
]
在最后
所以这images
将只包含
[
[
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "marine-transportation-transports-maritimes.xml"
},
{
"image_link": "1969.1523.001.aa.cs.jpg",
"catalogue_number": "1969.1523",
"dataset_name": "railway-transportation-transports-ferroviaires.xml"
}
]
]
我使用的set
功能
set.__doc__
'set() -> new empty set object\nset(iterable) -> new set object\n\nBuild an unor
dered collection of unique elements.'
我跟踪日志:
list(set(images))
Traceback (most recent call last):
File "<input>", line 1, in <module>
TypeError: unhashable type: 'list'
,使其更简单我怎么能删除所有重复在这个例子中
example = [ [{'a':1, 'b':2}, 'w', 2], [{'a':1, 'b':2}, 'w', 2] ]
#result
#example = [[{'a':1, 'b':2}, 'w', 2] ]
unhashable类型:“名单” 这意味着它不能哈希列表,因为列表是可变的,你不能哈希一个可变对象,如果你的数据是静态的,你可以改变列表的元组。 – danielfranca 2015-02-24 11:43:08
与字典的问题是,即使您将它们变为元组(不可变),您也没有任何方法来定义元素顺序,这会破坏比较。 一个好的解决方案将涉及将这个数据结构转换为不可变的可排序数据结构,然后清除重复项(例如使用'set')。 – Lachezar 2015-02-24 11:53:44