Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python list of lists contain substring

I have the list_of_lists and I need to get the string that contains ‘height’ in the sublists and if there is no height at all I need to get ‘nvt’ for the whole sublist.

I have tried the following:

list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]

_lists = []

for list in list_of_lists:
    list1 = []
    for st in list:
        if ("height" ) in st:
            list1.append(st)
        else:
            list1.append('nvt')
        _lists.append(list1)

OUT = _lists

the result I need to have is :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

_lists = ['nvt', 'height=4']

what I’m getting is:

_lists =  [['nvt','nvt'],['nvt','nvt','height=4']]

>Solution :

This is a good case for implementing a for/else construct as follows:

list_of_lists = [['width=9','length=3'],['width=6','length=4','height=4']]

result = []

for e in list_of_lists:
    for ss in e:
        if ss.startswith('height'):
            result.append(ss)
            break
    else:
        result.append('nvt')
        
print(result)

Output:

['nvt', 'height=4']

Note:

This could probably be done with a list comprehension but I think this is more obvious and probably has no significant difference in terms of performance

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading