简体   繁体   中英

Sum of specific elements in list of integers

I have to write a script for a burnout questionnaire that at the end of the script will give me scores for three subscales. I defined a list with all 22 questions of the questionnaire and a list that stores all answers. Now, I have the list of answers (called Answerlist ) with 22 values (RatingScale, low = 0, high = 6). With the numpy library I know how to sum all values

total = numpy.sum(Answerlist)

What I don't know is how to select the relevant items/questions for each subscale. I tried

subscale1 = numpy.sum(Answerlist[:, [0, 1, 2, 5, 7, 12, 13, 15, 19]])

subscale2 = numpy.sum(Answerlist[:, [4, 9, 10, 14, 21]]) 

but I get the error TypeError: list indices must be integers or slices, not tuple .

If Answerlist is a 1D array, then you would index it as follows

subscale1 = numpy.sum(Answerlist[[0, 1, 2, 5, 7, 12, 13, 15, 19]])

subscale2 = numpy.sum(Answerlist[[4, 9, 10, 14, 21]]) 

For example

>>> data = np.random.randint(0,6,22)
>>> data
array([2, 4, 1, 0, 2, 0, 2, 1, 3, 4, 1, 2, 3, 2, 1, 0, 1, 0, 5, 3, 3, 1])
>>> data[[1,12,18]]
array([4, 3, 5])
>>> np.sum(data[[1,12,18]])
12

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM