匹配列表基于其值的索引

时间:2019-01-19 16:07:15

标签: python list dictionary indexing

我是Python的新手,正在研究一个必须将索引列表与具有2个条件的值列表进行匹配的问题:

  1. 如果有重复的索引,则应将值相加
  2. 如果列表中没有索引,则值应为0

例如,以下是我的2个列表:“印度列表”和“瓦尔斯列表”。因此,在索引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]

我已经为它苦苦挣扎了几天,在网上找不到任何可以指引我正确方向的东西。谢谢。

5 个答案:

答案 0 :(得分:0)

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

   col1  col2  col3  col4  col5  col6   avg_even    avg_odd
0     1     7    56  16.0   1.0    13  12.000000  19.333333
1     2    45    67   NaN   9.0     3  24.000000  26.000000
2     3    12     8  25.0  23.0    53  30.000000  11.333333
3     4    56    12   6.0  56.0    72  44.666667  24.000000
4     5    14    39  19.0   NaN    88  40.333333  22.000000

答案 1 :(得分:0)

答案代码为

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]

希望有帮助

如果您不了解任何步骤,请发表评论

答案 2 :(得分:0)

您可以做的是按照升序对索引和值进行排序,然后对其进行汇总。这是示例代码:

import numpy as np

ind = [0,1,4,2,2]
vals = [5,4,3,2,1]

points = zip(ind,vals)

sorted_points = sorted(points)

new_ind = [point[0] for point in sorted_points]
new_val = [point[1] for point in sorted_points]

output = np.zeros((len(new_ind)))

for i in range(len(new_ind)):
    output[new_ind[i]] += new_val[i]    

在此代码中,索引值按升序排序,然后根据排序后的索引数组重新排列值数组。然后,使用简单的for循环,可以对每个现有索引的值求和并计算输出。

答案 3 :(得分:0)

 - /usr/app/node_modules

输出:

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)

答案 4 :(得分:0)

这是一个分组问题。您可以使用collections.defaultdict构建字典映射,在每次迭代中增加值。然后使用列表理解:

indices = [0,1,4,2,2]
values = [5,4,3,2,1]

from collections import defaultdict
dd = defaultdict(int)
for idx, val in zip(indices, values):
    dd[idx] += val

res = [dd[idx] for idx in range(max(dd) + 1)]

## functional alternative:
# res = list(map(dd.get, range(max(dd) + 1)))

print(res)
# [5, 4, 3, 0, 3]
相关问题