user9080591
user9080591

Reputation:

How to convert values inside nested lists into sets?

I was wondering if anyone has any ideas of how to convert the values contained in nested lists, so you end up with a list of a list of sets? e.g I have:

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

I am trying to convert this so the 0 is {0}, 1 is {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?

Upvotes: 4

Views: 7340

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122082

set() takes the values from an iterable and adds each value separately. You passed in an int, which is not iterable at all.

You would have to wrap your individual values in an iterable, like a list:

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

A much easier option would be to use the {...} set literal notation:

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

If the list doesn't need updating in place, you can also use a nested list comprehension to create a new list-of-lists-of-sets structure:

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

If you must update in place, at least just iterate over the outer rows, and use enumerate() to generate the indices for the inner columns:

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

If you have other references to the original list of lists, stick with with setting the values directly, otherwise use the list comprehensions. Both work:

>>> 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}]]

Upvotes: 4

Cory Kramer
Cory Kramer

Reputation: 117876

You can pass each element in {} to create a set, otherwise you have to pass set() an iterable sequence, which a single integer is not.

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

Upvotes: 4

Related Questions