Reputation: 143
I have scores from a questionnaire:
list= [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4, 3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1, 2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]
Certain questions need to be reverse-scored. "Rscores" is the list of indexes that need to be reverse-scored, this means that for those scores, if it's 1, then it needs to be replaced with a 4 and if it's a 2, it needs to be replaced with a 3.
Rscores = [1, 6, 11, 16, 21, 28, 33, 38, 43, 49, 57, 8, 46, 2, 7, 12, 17, 22, 25, 35, 40]
I have tried this, and many variations of it, but it doesn't work:
for Rscores in list:
if list[Rscores] == 1:
list[Rscores] = 4
elif list[Rscores] == 2:
list[Rscores] = 3
elif list[Rscores] == 3:
list[Rscores] = 2
elif list[Rscores] == 4:
list[Rscores] = 1
If anyone can help, I would be very grateful. Thanks in advance
Upvotes: 0
Views: 313
Reputation: 369
it;s working
list= [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4, 3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1, 2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]
for n, i in enumerate(list):
if i == 1:
list[n] = 4
if i == 2:
list[n] = 3
if i == 3:
list[n] = 2
if i == 4:
list[n] = 1
print(list)
Hope it's help full
Upvotes: 0
Reputation: 792
L = [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4, 3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1, 2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]
Rscores = [1, 6, 11, 16, 21, 28, 33, 38, 43, 49, 57, 8, 46, 2, 7, 12, 17, 22, 25, 35, 40]
def reverseScore(score):
if score == 1:
return 4
elif score == 2:
return 3
elif score == 3:
return 2
elif score == 4:
return 1
def rscoredList(L):
for idx in Rscores:
if idx < len(L):
L[idx] = reverseScore(L[idx])
return L
L = rscoredList(L)
I think a problem in the example you listed is that you have indices in your Rscores
that are outside the range of your list. (57 is listed as a to be reversed index tho it can't be because len(L)==42
.)
Upvotes: 0
Reputation: 37043
This creates a new list, with the necessary scores rectified.
lst= [1, 2, 2, 4, 1, 4, 1, 3, 2, 2, 2, 1, 1, 1, 4,
3, 4, 2, 1, 1, 1, 1, 1, 2, 2, 2, 4, 1, 4, 1,
2, 4, 4, 4, 4, 4, 2, 3, 2, 3, 3, 3]
Rscores = [1, 6, 11, 16, 21, 28, 33, 38, 43, 49, 57,
8, 46, 2, 7, 12, 17, 22, 25, 35, 40]
rectified_scores = [5-x if i in Rscores else x for i, x in enumerate(lst)]
enumerate
yields a sequence of pairs (i, x), where i
is the element index and x
is its value. 5-x if i in Rscores else x
is the score for a standard index, and the inverse of the score for indexes in the Rscores
list.
I renamed your list to avoid "shadowing" the name of a Python type. Your code would probably run marginally faster if Rscores
were a set, but it's not screaming to be optimised.
Upvotes: 1