'Remove element from one list based on elements in another list
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])
Solution 1:[1]
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)]
Solution 2:[2]
you can use zip:
for o, r in zip(options, right_answer):
o.remove(r)
print(options)
Solution 3:[3]
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']]
Solution 4:[4]
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']]
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 | Samathingamajig |
Solution 2 | warped |
Solution 3 | baskettaz |
Solution 4 |