-1

I have the following list: which stores index references (read in from a file).

easy_answers=[row[ca],row[1],row[2],row[3],row[4]]

Example values:

row[ca] = 1 #this is a flag that points to the right response, in this case row1 which is a
row[1] =  a
row[2] =  b
row[3] =  c
and so on

All I want to do is simply check the list to see if the index of any of the held list elements are the same (duplicate), and if so, remove the duplicate index (but leave in the row[ca] value, as that is the correct answer)

In the above example, the expected output would be:

easy_answers=[row[ca],row[1],row[2],row[3],row[4]]
#we know from the values that row[ca] = 1 and row[1] =1, so remove row[1]

..So the final output would be:

easy_answers=[row[ca],row[2],row[3],row[4]]

Code

Removing a duplicate from a list when dealing with just values is simple, but how do I change the code below to search for the values held by the index numbers to achieve the same thing?

ca=int(row[5]) #this is the right resopnse for the question
               easy_answers=[row[ca],row[1],row[2],row[3],row[4]]

            if row[ca] in easy_answers:

                  easy_answers.remove(row[ca])
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Compoot
  • 2,227
  • 6
  • 31
  • 63

2 Answers2

1

Rather than adding and then deduplicating, you may be better off removing the correct answer and then re-adding it later.

import random

correct_answer = 2
num_choices = 3
possibles = [1, 2, 3, 4]
#
if len(possibles) != num_choices:
    possibles.remove(correct_answer)
    random.shuffle(possibles)
    possibles = possibles[:num_choices - 1]
    possibles.append(correct_answer)
random.shuffle(possibles)
Glenn Rogers
  • 351
  • 2
  • 4
0

This function just create list again, but do not append values if they are already exist. So It will never delete CA If its always first.

easy_answers = [*values*]

def delete_duplicates_from_list(seq):
    seen = set()
    seen_add = seen.add
    return [x for x in seq if not (x in seen or seen_add(x))]
delete_duplicates_from_list = (easy_answers)

https://stackoverflow.com/a/480227/6333890

Jefferson Houp
  • 858
  • 1
  • 7
  • 17