匹配列表基于其值的索引

2024-10-01 15:48:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手,正在研究一个问题,在这个问题中,我必须用两个条件将索引列表与值列表相匹配:

  1. 如果有一个重复的索引,那么这些值应该求和
  2. 如果列表中没有索引,则值应为0

例如,下面是我的两个列表:“IND列表”和“VAL列表”。所以在索引0处,我的值是5;在索引1处,我的值是4;在索引2处,我的值是3(2+1),在索引3处,我的值可能是0(因为没有与索引相关的值),依此类推。你知道吗

Input:

'List of Inds' = [0,1,4,2,2]
'List Vals' = [5,4,3,2,1]
Output = [5,4,3,0,3]

我已经挣扎了几天,在网上找不到任何能为我指明方向的东西。非常感谢。你知道吗


Tags: of列表inputoutputval条件listind
3条回答
List_of_Inds = [0,1,4,2,2]
List_Vals = [5,4,3,2,1]
dic ={}

i = 0
for key in List_of_Inds:
    if key not in dic:
        dic[key] = 0
    dic[key] = List_Vals[i]+dic[key]
    i = i+1

output = []
for key in range(0, len(dic)+1):
    if key in dic:
        output.append(dic[key])
    else:
        output.append(0)

print(dic)
print(output)

输出:

{0: 5, 1: 4, 4: 3, 2: 3}
[5, 4, 3, 0, 3]

下面的代码根据需要工作。在计算机科学中,它被称为“稀疏矩阵”,其中数据仅为所述索引保留,但从外部看,数据结构的“虚拟大小”似乎很大。你知道吗

import logging

class SparseVector:
    def __init__(self, indices, values):
        self.d = {}
        for c, indx in enumerate(indices):
            logging.info(c)
            logging.info(indx)
            if indx not in self.d:
                self.d[indx] = 0
            self.d[indx] += values[c]

    def getItem(self, key):
        if key in self.d:
            return self.d[key]
        else:
            return 0

p1 = SparseVector([0,1,4,2,2], [5,4,3,2,1])
print p1.getItem(0);
print p1.getItem(1);
print p1.getItem(2);
print p1.getItem(3);
print p1.getItem(4);
print p1.getItem(5);
print p1.getItem(6);

答案代码为

def ans(list1,list2):
    dic={}
    ans=[]
    if not(len(list1)==len(list2)):
        return "Not Possible"
    for i in range(0,len(list1)):
        ind=list1[i]
        val=list2[i]
        if not(ind in dic.keys()):
            dic[ind]=val
        else:
            dic[ind]+=val
    val=len(list1)
    for i in range(0,val):
        if not(i in dic.keys()):
            ans.append(0)
        else:
            ans.append(dic[i])
    return ans

要测试:

  print(ans([0,1,4,2,2], [5,4,3,2,1]))

输出:

  [5, 4, 3, 0, 3]

希望有帮助

如果你不理解任何步骤,请发表评论

相关问题 更多 >

    热门问题