Get a set of 2d list in python

吃可爱长大的小学妹 提交于 2021-02-05 08:54:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!