Python - Return True If Strings Found In Nested List
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']]
Solution 1:
Try this:
contains = any([True for sublist in list1 if "1" in sublist and "MSG1" in sublist])
Solution 2:
You can use set.issubset
:
any(True for sub_list in list1 if {'1', 'MSG1'}.issubset(set(sub_list)))
Solution 3:
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
Solution 4:
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
Solution 5:
It's:
any(all(item in sublist for item in ['1', 'MSG1']) for sublist in list1)
Post a Comment for "Python - Return True If Strings Found In Nested List"