Home > Software engineering >  python Replace double list with appropriate dictionary format
python Replace double list with appropriate dictionary format

Time:06-15

We're writing a function that converts sparse lists into dictionaries

sp2([ [a,0,0],
      [0,e,0],
      [0,h,i] ]) == {(0,0):a, (1,1):e, (2,1):h, (2,2):i}

I want this kind of motion

I wrote something in one dimension

def sparse(ns): 
    dic = {}
    index = 0
    for n in ns:   
        if n != 0:
            dic[index] = n   
        index  = 1
    return dic

result:

# print(sparse([]))                        # {}
# print(sparse([0,0,3,0,0,0,0,0,0,7,0,0])) # {2: 3, 9: 7}

How do you change a one-dimensional thing to two-dimensional?

CodePudding user response:

Just add another inner loop:

def sparse(ns):
    dic = {}
    for i, row in enumerate(ns):
        for j, val in enumerate(row):
            if val != 0:
                dic[(i, j)] = val
    return dic

CodePudding user response:

You can do this with a simple nested dict comprehension and enumerate:

>>> a, e, h, i = 'a', 'e', 'h', 'i'
>>> m = [ [a,0,0],
...       [0,e,0],
...       [0,h,i] ]
>>> {(i, j): x for i, row in enumerate(m) for j, x in enumerate(row) if x}
{(0, 0): 'a', (1, 1): 'e', (2, 1): 'h', (2, 2): 'i'}
  • Related