How to convert values ​​inside nested lists to sets?

I was wondering if anyone has any ideas on how to convert the values ​​contained in nested lists so that you get a list of a list of sets? For example, I have:

[[0, 1, 2, 3, 4, 0, 6, 7, 8], [1, 4, 5, ...], ...]

I'm trying to convert it to 0was {0}, 1I am {1}. i.e:.

[[{0}, {1}, {2}, {3}, {4}, {0}, {6}, {7}, {8}], [{1}, {4}, {5}, ...], ...]

I currently have:

def ToSets(list):
    for i in range(0,9): #row
        for j in list[i]:
            list[i][j] = set(list[i][j])
   print(list)

I keep getting this error:

TypeError: 'int' object is not iterable

Does anyone know how I can fix this?

+4
source share
2 answers

set()takes values ​​from the iteration and adds each value separately. You went through int, which is not iterable at all.

You would need to wrap your individual values ​​in an iterable, for example a list:

list[i][j] = set([list[i][j]])

- {...}:

list[i][j] = {list[i][j]}

, , , :

def to_sets(l):
    return [[{i} for i in row] for row in l]

, enumerate() :

def to_sets_inplace(l):
    for row in l:
        for i, value in enumerate(row):
            row[i] = {value}

, , . :

>>> def to_sets(l):
...     return [[{i} for i in row] for row in l]
...
>>> demo = [[0, 1, 2, 3, 4, 0, 6, 7, 8], [1, 4, 5]]
>>> def to_sets_inplace(l):
...     for row in l:
...         for i, value in enumerate(row):
...             row[i] = {value}
...
>>> to_sets(demo)
[[{0}, {1}, {2}, {3}, {4}, {0}, {6}, {7}, {8}], [{1}, {4}, {5}]]
>>> to_sets_inplace(demo)
>>> demo
[[{0}, {1}, {2}, {3}, {4}, {0}, {6}, {7}, {8}], [{1}, {4}, {5}]]
+5

{}, , set() , .

>>> data = [[1,2,3],[4,5,6]]
>>> [[{j} for j in i] for i in data]
[[{1}, {2}, {3}], [{4}, {5}, {6}]]
+3
source

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


All Articles