Python 2-D list how to make a set

as a python list follow

list1 = [[1,2],[3,4],[1,2]]

I want to create a set so that I can create unique list items like

list2 = [[1,2],[3,4]].

Is there any function in python that I can use. Thanks

+1
source share
6 answers

This will do:

>>> list1 = [[1,2],[3,4],[1,2]]
>>> list2 = list(map(list, set(map(tuple,list1))))
>>> list2
[[1, 2], [3, 4]]
+3
source

Unfortunately, there is no single built-in function that can handle this. The lists are not shaking (see this SO post) . So you cannot have setfrom listin Python.

But the tuples are hashed:

l = [[1, 2], [3, 4], [1, 2]]
s = {tuple(x) for x in l}

print(s)

# out: {(1, 2), (3, 4)}

, , , , append, , . , uniquification .

+1

, , . : [[1,2,3], [1,2], [1]][[1,2,3], [1,2], [1]]

>>> print map(list, {tuple(sublist) for sublist in list1})
[[1, 2], [3, 4]]
+1

:

list1 = [[1,2],[3,4],[1,2]]
list2 = []
for i in list1:
    if i not in list2:
        list2.append(i)
print(list2)
[[1, 2], [3, 4]]
0

, :

Python 2.x

list1 = [[1, 2], [3, 4], [1, 2]]
list2 = {str(v): v for v in list1}.values()

Python 3.x

list1 = [[1, 2], [3, 4], [1, 2]]
list2 = list({str(v): v for v in list1}.values())
0

There is no integrated single function to achieve this. You got a lot of answers. In addition to these, you can also use the function lambdato achieve this goal:

list(map(list, set(map(lambda i: tuple(i), list1))))
0
source

Source: https://habr.com/ru/post/1652208/


All Articles