Python - Return true if strings found in nested list

Viewed 83

My goal is to return True/False if I am able to detect two items within a nested list.

E.g.

list1 = [['1', 'sjndnjd3', 'MSG1'], ['2', 'jdakb2', 'MSG1'], ['1', 'kbadkjh', 'MSG2']]

I want to iterate over this list to confirm if I can find '1' & 'MSG1' within a nested list. Important to note I only want this to return true if both items are found and if they're found within the same nested list.

I've tried various combinations of the below however I cannot get it quite right.

all(x in e for e in list1 for x in ['1', 'MSG1'])

Any assistance is greatly appreciated.

6 Answers

Try this:

contains = any([True for sublist in list1 if "1" in sublist and "MSG1" in sublist])

You can use set.issubset:

any(True for sub_list in list1 if {'1', 'MSG1'}.issubset(set(sub_list)))

You need to apply all to each test of 1 and MSG being in list1, so you need to rewrite your list comprehension as

found = [all(x in e for x in ['1', 'MSG1']) for e in list1]
# [True, False, False]

You can then test for any of those values being true:

any(found)
# True

You can make a function as follows, using sum and list's count method:

def str_in_nested(list_, string_1, string_2):
    return sum(sub_list.count(string_1) and sub_list.count(string_2) for sub_list in list_) > 0

Applying this function to you current case:

>>> list1 = [['1', 'sjndnjd3', 'MSG1'], ['2', 'jdakb2', 'MSG1'], ['1', 'kbadkjh', 'MSG2']]
>>> str_in_nested(list1, '1', 'MSG1')
True

It's:

any(all(item in sublist for item in ['1', 'MSG1']) for sublist in list1)

Give this a try...

for item in list1:
    all(i in item for i in sub)
Related