简体   繁体   English

稀疏向量Python字典

[英]Dictionary to Sparse Vector Python

please help me on this homework: 请帮我做这个作业:

makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1}) makeA({0:1,2:2,1,4:2,6:1,9:1})

the output should be like this: 输出应该是这样的:

[1, 0, 1, 0, 2, 0, 1, 0, 0, 1]

Try a list comprehension: 尝试列表理解:

def makeA(d, default=0):
    """Converts a dictionary to a list. Pads with a default element

    Examples:

    >>> makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})
    [1, 0, 1, 0, 2, 0, 1, 0, 0, 1]

    >>> makeA({3: 'kos'},'')
    ['', '', '', 'kos']

    """
    maxElem = max(d)
    return [d.get(x, default) for x in range(maxElem+1)]

The first line of the function body finds the maximum key in the dict (because dict objects yield their keys when iterated over). 函数主体的第一行在dict中找到最大键(因为dict对象在迭代时会产生其键)。 If the maximum key is 5, you'd need an array of 6 elements [0..6]. 如果最大键为5,则需要包含6个元素的数组[0..6]。

The last line uses a list comprehension over a sequence 0 .. maxElem , and for each value of this sequence, assigns either d 's value for this key or 0 if not present. 最后一行在序列0 .. maxElem上使用列表0 .. maxElem ,并为此序列的每个值分配d的值(如果不存在)为此键或0。

Yes, you could do the default value in list comprehension. 是的,您可以在列表理解中使用默认值。 But I think it's nicer style to let the defaultdict class do it for you. 但是我认为让defaultdict类为您做到这一点更好。 And you get more readable code to boot!! 这样您就可以启动更多可读的代码! :-) :-)

from collections import defaultdict

def makeA(d):
    dd = defaultdict(int, d)
    return [dd[n] for n in range(10)]


print makeA({0: 1, 2: 1, 4: 2, 6: 1, 9: 1})

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

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