stumped221 stumped221 - 1 year ago 47
Python Question

Python delete from list of lists based on a list

I need to delete a list from a list of lists based off a second list. I have the following:

LA = []
LA.append([u'02fc0b', u'val1', u'val2'])
LA.append([u'0a1ac', u'val1', u'val2'])
LA.append([u'02fc0b', u'val1', u'val2'])
LA.append([u'safsdf', u'val1', u'val2'])
LA.append([u'lmuylj', u'val1', u'val2'])


EXCL = []
EXCL.append('02fc0b')
EXCL.append('safsdf')


And I'd like to exclude any list in LA[] where the value in position 0 appears in EXCL[]. I can totally do this with a loop, but I feel like there is a more Pythonic approach to use, and I'd love to learn.

Answer Source

you could use filter with custom condition:

LA = []
LA.append([u'02fc0b', u'val1', u'val2'])
LA.append([u'0a1ac', u'val1', u'val2'])
LA.append([u'02fc0b', u'val1', u'val2'])
LA.append([u'safsdf', u'val1', u'val2'])
LA.append([u'lmuylj', u'val1', u'val2'])


EXCL = []
EXCL.append('02fc0b')
EXCL.append('safsdf')

d = set(EXCL)
print(list(filter(lambda v: v[0] not in d, LA)))
#[['0a1ac', 'val1', 'val2'], ['lmuylj', 'val1', 'val2']]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download