my_list = [[u'polySurface5.e[4]', u'polySurface5.e[1]', .5], [u'polySurface5.e[8]', u'polySurface5.e[2]', .9], [u'polySurface5.e[1]', u'polySurface5.e[4]', .5], [u'polySurface5.e[2]', u'polySurface5.e[9]', 1.2], [u'polySurface5.e[2]', u'polySurface5.e[2]', 0] ]
new_list = []
my_set = set()
for sublist in my_list:
if sublist[2] != 0:
frozen_sub = frozenset(sublist)
if not frozen_sub in my_set:
new_list.append(sublist)
my_set.add(frozen_sub)
结果:
>>> new_list
[[u'polySurface5.e[4]', u'polySurface5.e[1]', 0.5], [u'polySurface5.e[8]', u'polySurface5.e[2]', 0.9], [u'polySurface5.e[2]', u'polySurface5.e[9]', 1.2]]
请注意,我将原始列表的名称更改list
为my_list
. 我这样做是因为list
is Python 中的一个关键字,但是通过调用 anobject
list
你正在隐藏它。看一下这个:
>>> list((1,2,3))
[1, 2, 3]
>>> list = [3,4,5]
>>> list((6,7,8))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
编辑:回答后续帖子。
set
是一个数据结构,只包含唯一的项目并且项目没有顺序。例如:
>>> set([1,2,2,4,4])
set([1, 2, 4])
>>> set([1,2,4]) == set([4,4,4,1,2])
True
frozenset
是类似于set的数据结构,但又有所不同。set
是可变的,而frozenset
不是;也就是说,我们可以将东西添加到 set 中,但不能添加到frozenset
. 但是,frozenset
是可散列的,而set
不是。这fozenset
可以是“字典”中的键或集合中的元素。
可变性:
>>> b = set([1,2,3])
>>> b.add(6)
>>> b
set([1, 2, 3, 6])
>>> d = frozenset([1,2,3])
>>> d.add(6)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
哈希性:
>>> b = set([1,2])
>>> d = set([5,3])
>>> g = set([b,d])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'set'
>>> b = frozenset([1,2])
>>> d = frozenset([5,3])
>>> g = set([b,d])
>>> g
set([frozenset([1, 2]), frozenset([3, 5])])
我希望这有帮助。