我想找到以下项目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所需项目后面的项目有数字.如何找到共同的项目均list1和list2,以及删除的项目list2不在list1(同时仍保持重叠项目后的零和的吗?)
# 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)
| 归档时间: |
|
| 查看次数: |
884 次 |
| 最近记录: |