如何在Python中从列表中删除不可损坏的重复项?

如何在Python中从列表中删除不可损坏的重复项?,python,Python,我的数据如下: [{u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': [u'/www/web'], u'server_port': u'80'}, {u'webpath': [u'/www/web'], u'server_port': u'80'}, {u'webpath': [u'/www/shanghu'], u'server_port': u'80'}, {u'webpath': [u'/www/shanghu']

我的数据如下:

[{u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': [u'/www/web'], u'server_port': u'80'}, {u'webpath': [u'/www/web'], u'server_port': u'80'}, {u'webpath': [u'/www/shanghu'], u'server_port': u'80'}, {u'webpath': [u'/www/shanghu'], u'server_port': u'80'}, {u'webpath': [u'/www/www/html/falv'], u'server_port': u'80'}, {u'webpath': [u'/www/www/html/falv'], u'server_port': u'80'}, {u'webpath': [u'/www/www/html/falv'], u'server_port': u'80'}, {u'webpath': [u'/www/falvhezi'], u'server_port': u'80'}, {u'webpath': [u'/www/test10'], u'server_port': u'80'}, {u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': u'/etc/html', u'server_port': u'80'}, {u'webpath': [u'/www/400.ask.com'], u'server_port': u'80'}, {u'webpath': [u'/www/www'], u'server_port': u'80'}, {u'webpath': [u'/www/www'], u'server_port': u'80'}, {u'webpath': [u'/www/www'], u'server_port': u'80'}, {u'webpath': [u'/www/zhuanti'], u'server_port': u'80'}, {u'webpath': [u'/www/zhuanti'], u'server_port': u'80'}, {u'webpath': [u'/www/shanghu'], u'server_port': u'80'}]
我的代码是:

    seen = set()
    new_webpath_list = []
    for webpath in nginxConfs:
        t = tuple(webpath.items())
        if t not in seen:
            seen.add(t)
            new_webpath_list.append(webpath)
但脚本返回:

TypeError: "unhashable type: 'list'"

您正在从字典中创建元组以使其可散列,但这些元组中仍然可能存在不可散列的列表!相反,您还必须对值进行“元组化”

t = tuple(((k, tuple(v)) for (k, v) in webpath.items()))
请注意,这有点浮躁,因为dict中的第一个条目只是一个字符串,而其他条目是字符串列表。您可以使用
if/else
来修复此问题,但实际上不需要这样做

t = tuple(((k, tuple(v) if isinstance(v, list) else v) for (k, v) in webpath.items()))
或者,您也可以只记住字典中的字符串表示形式

t = repr(webpath)

最直接的方法是直接使用您正在构建的新列表测试成员资格

new_webpath_list = []
for webpath in nginxConfs:
    if webpath not in new_webpath_list:
        new_webpath_list.append(webpath)

这将处理存在任意(事先未知)级别的不可损坏类型嵌套的情况。它还使您的代码更简单、更容易理解,而且可能更高效,因为您没有创建不需要的额外数据(没有
seen
set,没有将元素转换为元组)。

迟了回答,但我能够使用以下方法从
列表中删除重复的
dict

old_list = [{"x": 1}, {"x": 1}, {"x": 2}]
new_list = []
[new_list.append(x) for x in old_list if x not in new_list]
# [{'x': 1}, {'x': 2}]

可能重复@muddyfish,但不适用。应提出相同的错误
.items()
不会将列表转换为元组。这仍然是一个重复的问题,只需谷歌搜索即可。您正在创建元组,但这些元组中仍然可能存在不可哈希的列表!