简体   繁体   中英

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])

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)]

Try it online!

you can use zip:

for o, r in zip(options, right_answer):
    o.remove(r)
    
print(options)
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']]

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']]

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