2

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.

2
  • Do you want to match two items within same group or is matching in different group is also required? Commented Mar 14, 2020 at 5:48
  • In the above instance, both '1' and 'MSG1' need to be within the same nested list. E.g. only list1[0] should match. In the event that list1 only contained list1[1] & list1[2], this should return false. Commented Mar 14, 2020 at 5:49

6 Answers 6

2

Try this:

contains = any([True for sublist in list1 if "1" in sublist and "MSG1" in sublist])
Sign up to request clarification or add additional context in comments.

Comments

1

You can use set.issubset:

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

Comments

1

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

1 Comment

Thanks for the explanation!
0

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

Comments

0

It's:

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

Comments

0

Give this a try...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.