Let's say there is a list of list. How can I loop through list's list 2nd element and check if all elements from other list are there?
list = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 9]
if all (item in list for item[1] in required):
log.debug('all items exist in nested list') //<- this should be printed
item[1]
is wrong in example and I can't figure out how to change it.
CodePudding user response:
lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [2, 5, 9]
checker = set()
for sublist in lst:
for elem in sublist:
if elem in required:
checker.add(elem)
if set(required) == checker:
log.debug('all items exist in nested list')
CodePudding user response:
with sets
lst_set = set(x[1] for x in lst)
required=set(required)
print(lst_set&required==required)
CodePudding user response:
Try this:
lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 9]
chk = [any(map(lambda x: r in x, lst)) for r in required]
# [True, True, True]
if all(chk):
print('all items exist in nested list')
Test with another required list
:
lst = [['foo', 2, 'bar'], ['foo', 5, 'bar'], ['foo', 9, 'bar'], ['foo', 12, 'bar']]
required = [ 2, 5, 11]
[any(map(lambda x: r in x, lst)) for r in required]
# [True, True, False]