python按索引求和

时间:2019-01-13 21:55:48

标签: python vector indexing

如果我有一个索引列表和一个值列表, 如何对重复索引的值求和?低于3的值将在索引中出现3次,因此val的总和为11。然后使用索引。

<smartFilterBar:ControlConfiguration
    key="MyOwnFilterField" index="1" label="Custom Filter Field"
    groupId="_BASIC" width="300px" mandatory="mandatory"
    visibleInAdvancedArea="true">

    <smartFilterBar:customControl>
      <m:Select id="foo" customData:hasValue="true">
        <core:Item key="1" text="ONE"/>
        <core:Item key="2" text="TWO"/>
        <core:Item key="3" text="THREE"/>
      </m:Select>
    </smartFilterBar:customControl>

</smartFilterBar:ControlConfiguration>

会返回

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]

1 个答案:

答案 0 :(得分:1)

这部分回答了您的问题,您必须告诉我们如何获取结果列表,下面的算法可让您跟踪重复索引并求和它的值并将其分配给ans。可以对其进行修改以满足您的需求。希望这会有所帮助:)

尝试一下:

A = [0,   3,   7,   3,   3,   5, 1]
B = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]

lookupDictionary = {}

for i, x in enumerate(A):
    if x in lookupDictionary:
        lookupDictionary[x].append(B[i]) # Element already in dictionary, append val
    else:
        lookupDictionary[x] = [B[i]] # Element not in dictionary so add as a list

result = []
for i in range(max(A) + 1):
    if i in lookupDictionary:
        result.append(sum(lookupDictionary[i]))
    else:
        result.append(0.0)
print(result)

# which will give you the answer
result = [1.0, 7.0, 0.0, 11.0, 0.0, 6.0, 0.0, 3.0]

我们将重复索引的值存储在字典中,然后将长度大于1的索引相加,并将其值分配给ans。