简体   繁体   中英

python Replace double list with appropriate dictionary format

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM