在list1中查找同样位于list2中的项目,并删除不在list1中的项目

use*_*545 2 python list

我想找到以下项目list1:

list1 = ['peach', 'plum', 'apple', 'kiwi', 'grape']
Run Code Online (Sandbox Code Playgroud)

也在list2:

list2 = ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', 'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1']
Run Code Online (Sandbox Code Playgroud)

问题是list2所需项目后面的项目有数字.如何找到共同的项目均list1list2,以及删除的项目list2不在list1(同时仍保持重叠项目后的零和的吗?)

Joc*_*zel 9

# using a set makes the later `x in keep` test faster
keep = set(['peach', 'plum', 'apple', 'kiwi', 'grape'])

list2= ['peach,0,1,1,0,1,0,1', 'carrot,1,0,1,1,0,1,1', 
        'lime,0,1,1,0,1,1,0', 'apple,0,1,1,0,1,1,1']

# x.split(',',1)[0] = the part before the first `,` 
new = [x for x in list2 if x.split(',',1)[0] in keep]
Run Code Online (Sandbox Code Playgroud)