问题
I have a list like follows
t=[[1, 7], [3, 7], [1, 7], [5, 8], [3, 7]]
I need to get a set out of this so the output would be like
t=[[1, 7], [3, 7], [5, 8]]
I tried to use t=set(t)
but it didn't work
回答1:
If you do not care about the order, you can first convert the inner lists
to tuples
using map()
function, and then convert them to set
and then back to list
.
Example -
>>> t=[[1, 7], [3, 7], [1, 7], [5, 8], [3, 7]]
>>> t = list(set(map(tuple,t)))
>>> t
[(3, 7), (5, 8), (1, 7)]
回答2:
The problem is that lists are mutable and thus one cannot make a set out of them as they might change. Thus you want to use tuples which are immutable. Thus you can use:
list(set([tuple(ti) for ti in t]))
回答3:
And if you do care about order:
def func(items):
seen = set()
for item in items:
item = tuple(item)
if item not in seen:
yield item
seen.add(item)
Or you simply subclass list and override append so no duplicates can be added in the first place:
class T(list):
def append(self, item):
if item not in self:
list.append(self, item)
Which would be used like this:
>>> t = T([[1, 7], [3, 7], [5, 8]])
>>> t
[[1, 7], [3, 7], [5, 8]]
>>> t.append([1, 7])
>>> t
[[1, 7], [3, 7], [5, 8]]
回答4:
Sets can only contain immutable elements. list
is mutable type, you need to convert items to immutable type, e.g. tuple
:
set(map(tuple, t))
来源:https://stackoverflow.com/questions/31053385/get-a-set-of-2d-list-in-python