【问题标题】:Get unique values from a nested list in python从python中的嵌套列表中获取唯一值
【发布时间】:2015-04-26 00:28:37
【问题描述】:

我有一个嵌套列表(列表列表),我想删除重复项,但出现错误。这是一个例子:

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 type: 'list' 这意味着它不能散列列表,因为列表是可变的,你不能散列一个可变对象,如果你的数据是静态的,你可以改变元组的列表。
  • dicts 的问题是即使你把它们变成元组(不可变的)你也没有办法定义元素的顺序,这会破坏比较。一个好的解决方案是将此数据结构转换为不可变的可散列数据结构,然后清除重复项(例如使用set)。

标签: python list python-2.7 python-3.x nested-lists


【解决方案1】:

好像你想要这样的东西,

>>> example = [ [{'a':1, 'b':2}, 'w', 2], [{'a':1, 'b':2}, 'w', 2] ]
>>> l = []
>>> for i in example:
        if i not in l:
            l.append(i)


>>> l
[[{'b': 2, 'a': 1}, 'w', 2]]

【讨论】:

  • 感谢@Avinash!我猜这个没有内置函数!
【解决方案2】:

set 和 dict 容器依赖于数据散列。其他可变容器,如 list(以及 set 和 dict 本身)不能被散列。它们稍后可能会更改(可变),因此恒定的哈希值没有意义。

但是您可以将所有数据转换为(嵌套)元组,最后转换为set。由于tuple 是一个不可变 容器 - 而且您的数据是可散列的(strings) - 它可以工作。对于您的特殊 images 案例,这是一个令人讨厌的单行代码,可以解决问题:

images_Set = set([tuple([tuple(sorted(image_dict.items())) 
    for image_dict in inner_list])  for inner_list in images])

和

print(images_set)

打印

{((('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')))}

编辑:字典的items 函数没有保证顺序。因此,我还添加了sorted以确保订单。

【讨论】:

  • 当你将字典翻译成元组时,元素的顺序如何? CPython implementation detail: Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. (docs.python.org/2/library/stdtypes.html#dict.items)
  • 感谢@SmCaterpillar 的解释。感谢 Kasra、Avinash 和 Lucho,你们也都有很好的答案。
【解决方案3】:

您可以使用compiler.ast.flatten 来展平您的列表,然后将您的字典转换为可散列的对象以抓取集合,然后再转换回 dict,只需一个列表理解即可:

>>> from compiler.ast import flatten
>>> [dict(item) for item in set(tuple(i.items()) for i in flatten(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'}]

【讨论】:

    猜你喜欢
    • 2018-03-23
    • 1970-01-01
    • 2016-12-27
    • 2022-10-12
    • 2021-05-31
    • 2016-03-10
    • 2012-10-05
    • 2021-01-15
    • 1970-01-01
    相关资源
    最近更新 更多