Test if all elements are in another list in Python -
i want test if reference_list contains of items in required_strings.
required_strings = ['apple','banana','carrot'] reference_list = [['apple','tree'], ['banana','grass'], ['carrot','grass']] i want true or false test result. expected answer 'true'.
this had attempted:
test = [i in reference_list if any(s in s in required_strings)] print test
you can making use of set , itertools.chain. we're going take advantage of set theory , regard required_strings , reference_list sets, , demonstrate required_strings <= reference_list; is, required strings set contained inside of reference list.
first, use itertools.chain flatten shallow list.
from itertools import chain chain(*reference_list) # iterable object next, turn both chained list , tested list sets , compare see if 1 set contained in other.
from itertools import chain set(required_strings) <= set(chain(*reference_list)) if you're keen on not using chain, can use sum(list_of_lists, []) reduce instead.
set(required_strings) <= set(sum(reference_lists, [])) however, encourage use set instead of list, sort of problem better suited towards set. don't have import it; can use class list.
Comments
Post a Comment