简体   繁体   中英

find items in list1 that are also in list2 and delete items not in list1

i want to find items that are in list1 :

list1 = ['peach', 'plum', 'apple', 'kiwi', 'grape']

that are also in 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']

the problem is that the items in list2 have numbers after the needed item. how do i find the common items in both list1 and list2 , and delete the items in list2 that are not in list1 (while still keeping the zeros and ones after the overlapping items?)

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

Psuedocode:

for each i in list1
    foreach j in list2
        if j.contains(i)
            list2.remove(j)

Treat j and i as strings, and look to see if each element contains the element from list1.

Cédric's answer (which was deleted but was a good inspiration, thanks to him) misses the point that you have a string including all the 0 and the 1. To be complete:

for item in list1:
    try:
       list2.remove(item.split(',')[0])
    except ValueError:
      pass

Max

Something like this may help(note that it will create new list object):

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]

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