在list1中查找同时在list2中的项目,并删除list1中不在的项目
我想找出在 list1
中的项目:
list1 = ['peach', 'plum', 'apple', 'kiwi', 'grape']
同时也在 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']
问题是,list2
中的项目后面有数字。我要怎么找到 list1
和 list2
中的共同项目,并删除那些不在 list1
中的 list2
项目(同时保留那些重叠项目后面的零和一)呢?
4 个回答
0
伪代码:
for each i in list1
foreach j in list2
if j.contains(i)
list2.remove(j)
把 j 和 i 当作字符串来处理,然后检查每个元素是否包含 list1 中的元素。
0
像这样可能会对你有帮助(注意,这样做会创建一个新的列表对象):
list1= ['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']
list2 = [x for x in list2 for y in list1 if x.split(',')[0]==y]
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]
当然可以!请把你想要翻译的内容发给我,我会帮你用简单易懂的语言解释清楚。