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

时间:2015-07-23 13:46:07

标签: 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'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'"

3 个答案:

答案 0 :(得分:2)

您正在使用字典创建元组以使其可以清除,但是仍然可以在里面这些元组中使用不可清除的列表!相反,你也必须" tuplefy"价值观。

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)

答案 1 :(得分:0)

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

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

这可以处理不可用类型的任意(未知的)嵌套级别的情况。它还使您的代码更简单,更易于理解,并且可能更高效,因为您没有创建不需要的额外数据(没有设置seen,没有元素转换为元组)。

答案 2 :(得分:0)

最新答案,但是我能够使用以下方法从dict中删除重复的list

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}]

Demo