2016-04-24 60 views
0

我是编程新手,我试图从列表中删除Python中的重复项。不过,我无法使用set()来执行它。列表包含IP地址和日期下面是我的代码,并列出从python列表中删除重复的元素

l = [['10.136.161.80', '2015-08-29'], ['10.136.161.80', '2015-08-29'], ['10.136.161.80', '2015-08-29'], ['10.136.161.80', '2015-08-29'], ['10.136.161.80', '2015-08-29'], ['10.136.161.80', '2015-08-29'],['10.136.161.235', '2016-03-12'], ['10.136.161.235', '2015-05-02'], ['10.136.161.93', '2016-03-12'], ['10.136.161.93', '2016-03-12'], ['10.136.161.93', '2015-04-25'], ['10.136.161.93', '2015-04-25'], ['10.136.161.93', '2016-03-12'], ['10.136.161.93', '2015-04-25'], ['10.136.161.93', '2015-04-25'], ['10.136.161.93', '2015-11-28'], ['10.136.161.93', '2015-11-28'], ['10.136.161.80', '2015-08-29'], ['10.136.161.112', '2015-04-25'], ['10.136.161.231', '2015-04-25']] 

fl = set(l) 
print fl 

我得到以下错误:

Traceback (most recent call last): 
    File "C:/Users/syeam02.TANT-A01/PycharmProjects/security/cleandata.py", line 18, in <module> 
    fl = set(array) 
TypeError: unhashable type: 'list' 

在此先感谢。

回答

3

您不能在set中使用list类型元素,因为list是可变实体。出于同样的原因,您不能使用list作为字典的关键字。你需要有一个不可变的类型,如tuple

所以,你可以内部元素的元组转换通过设置前:

set(tuple(li) for li in l) 

检查this section to doc

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain a heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

+0

感谢罗希特这个解决我的问题。 现在我的数据看起来像这样我们有不同的日期和IP是一样的可以只保留一个日期和IP 2015-08-29 10.136.161.80 2015-04-25 10.136.161.93 2015-04-25 10.136.161.231 2015年11月28日10.136.161.93 2016年4月2日10.136.161.231 2015年8月8日10.136.161.231 2015年11月28日10.136.161.235 2016年3月12日10.136.161.235 2015年-04-25 10.136.161.112 2015-05-02 10.136.161.235 2016-03-12 10.136.161.93 2015-11-28 10.136.161.231 2016-03-12 10.136.161.231 –