I have Two lists like this:
options = [['64', '32', '42', '16'], ['Sit', 'Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat', 'Puppy']]
right_answer = ['42', 'Sit', 'Puppy']
I want to remove the right_answer from options and get an output like this:
incorrect_answer = [['64', '32', '16'], ['Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat']]
I tried using .remove() but it clears the list:
for i in range(0,len(options)):
incorrect_answers = options[i].remove(right_answer[i])
CodePudding user response:
A simple list comprehension with zip
that doesn't mutate the original lists
incorrect_answers = [[answer for answer in possible if answer != correct] for possible, correct in zip(options, right_answer)]
CodePudding user response:
you can use zip:
for o, r in zip(options, right_answer):
o.remove(r)
print(options)
CodePudding user response:
options = [['64', '32', '42', '16'], ['Sit', 'Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat', 'Puppy']]
right_answer = ['42', 'Sit', 'Puppy']
print([[e for e in opt if e not in right_answer] for opt in options])
Result:
[['64', '32', '16'], ['Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat']]
CodePudding user response:
You can use a simple loop with list comprehension to retain elements not in the right answers.
incorrect_answers = []
for i, my_list in enumerate(options):
incorrect_answers.append([x for x in my_list if x != right_answer[i]])
print(incorrect_answers)
# [['64', '32', '16'], ['Beg', 'Shake', 'Catch'], ['Lion', 'Dog', 'Cat']]