'how to find the sum of list indexes which are given in the sublists of another list in python
i have given a list
myLIST=[34 , 54 , 65 , 76 , 88 , 23 , 56 , 76 , 43]
and a list with the index numbers of myLIST in sublist (assume myLIST starts from index 1)
indexLIST=[{1,2,3} , {4,5,7} , {6,8,9}]
my task is to add the indexes of myLIST according to the sublists of indexLIST
[{34+54+65} , {76,88,23} , {56,76,43}]
res=[153 ,187 , 175]
Note: the sublists of indexLIST are python sets
Solution 1:[1]
So first of all there is either a mistake in your indexLIST (set 2 should be {4, 5, 6} and set 3 {7, 8, 9}) or your res (which with the given indexLIST is [153, 220, 142]) otherwise you can just do something like this:
res: list[int] = list()
for set in indexLIST:
tmp = 0
for idx in set:
tmp += myLIST[idx - 1]
res.append(tmp)
Solution 2:[2]
My approach would be to iterate over the sets of indices in index_list and then map these sets to the values of my_list. With sum() I then can compute the sum of each list of values:
my_list=[34 , 54 , 65 , 76 , 88 , 23 , 56 , 76 , 43]
index_list=[{1,2,3} , {4,5,7} , {6,8,9}]
result = [sum(map(lambda x: my_list[x-1], d)) for d in index_list]
print(result)
Output:
[153, 220, 142]
Solution 3:[3]
myLIST=[34 , 54 , 65 , 76 , 88 , 23 , 56 , 76 , 43]
indexLIST=[{1,2,3} , {4,5,6} , {7,8,9}]
from pprint import pprint
pprint([sum([myLIST[j-1] for j in i])for i in indexLIST])
Result:
[153, 220, 142]
P.S.
This type of indexing which you're trying to achive could be very fragile, e.g. what if the index, which you're giving doesn't exist in your list ->IndexError ...?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | CaptainJack42 |
| Solution 2 | JANO |
| Solution 3 | baskettaz |
