首页 文章

从字典创建列表,按索引指定位置并跳过某些索引位置

提问于
浏览
-1

我正在使用以下字典:

d = {'inds':[0, 3, 7, 3, 3, 5, 1], 'vals':[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]}

我想创建一个new_list,它接受列表 d['vals'] 中的值,并通过列表 d['inds'] 中的相应索引将它们放在new_list中 . 最终结果应该是:

[1.0, 7.0, 0.0, 11.0, 0.0, 6.0, 0.0, 3.0]

这需要以下内容:

d['inds'] == [0,   3,   7,   3,   3,   5,   1]

d['vals'] == [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

对于未包含在 d['inds'] 中的任何索引位置,相应的值为0.0 .

对于重复的索引位置,该位置的 True 值是各个值的总和 . 例如,3以上重复3次;所以, new_list[3] 应该 == 11 ,这是2.0 4.0 5.0的总和 .

2 回答

  • 2

    首先,分配一个适当长度和满零的列表:

    result = [0] * (max(d['inds']) + 1)
    

    然后遍历索引和值并将它们添加到列表中的值:

    for ind, value in zip(d['inds'], d['vals']):
        result[ind] += value
    

    输出:

    >>> result
    [1.0, 7.0, 0, 11.0, 0, 6.0, 0, 3.0]
    
  • 0

    在与帮助我完成此操作的同事合作之后,获得了以下内容以获得更加动态的功能(允许不同长度的结果列表):

    import numpy as np
    d ={
        'inds': [0,3,7,3,3,5,1],
        'vals': list(range(1,8))}  
        ## this assumes the values in the list associated with the 'vals' key
        ## remain in numerical order due to range function.  
    
    
    def newlist(dictionary, length) ##length must be at least max(d['inds'])+1
        out = np.zeroes(length)
        for i in range (len(dictionary['inds'])):
            out[dictionary['inds'][i]] += d['vals'][i]
    
        return(out)
    

相关问题