简体   繁体   English

python用适当的字典格式替换双列表

[英]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 :您可以使用简单的嵌套字典理解和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'}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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