我有一個嵌套列表(列表的列表),我想刪除重複,但我得到一個錯誤。這是一個例子:從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