0

Let's say I have a list such as:

example_of_list = [[['aaaa'],['bbbb'],['cccc']], [['aabsd'],['fdwewd'],['dsfss']], [['sssss'],['ddddd'],['fffff']]]

And I want to check if my_list contains a substring

sub_sting = 'aaa'

So, In that case, this will give 'True' because I have 'aaaa' on the list as a sublist.

How to check this thing?

I already considered 'in' or 'str.contains', but it seems it doesn't give a proper response.

Dong-gyun Kim
  • 411
  • 5
  • 23

2 Answers2

2

Here is a possible solution:

from itertools import chain

def contains(lst, substr):
    return any(substr in s for s in chain(*chain(*lst)))

You can use the function in this way:

lst = [[['aaaa'], ['bbbb'], ['cccc']],
       [['aabsd'], ['fdwewd'], ['dsfss']],
       [['sssss'], ['ddddd'], ['fffff']]]
substr = "aaa"

print(contains(lst, substr)) # True
Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
1

You could flatten the list, then iterate through it. I got the flatten function from What is the fastest way to flatten arbitrarily nested lists in Python?

example_list = [[['aaaa'],['bbbb'],['cccc']], [['aabsd'],['fdwewd'],['dsfss']], [['sssss'],['ddddd'],['fffff']]]

def flatten(container):
    for i in container:
        if isinstance(i, (list,tuple)):
            for j in flatten(i):
                yield j
        else:
            yield i

new_list = list(flatten(example_list))
for elem in new_list:
    if ('aaa' in elem):
        print(elem)
Sri
  • 2,281
  • 2
  • 17
  • 24