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

Create list of arrays that contain specific element

I need to create a function that searches if certain string is within an array and create a list with all the elements (lists) that contain it. For example:

word = 'busy'
array = [[['99', 'Normal', [], ['busy', '0'], 28016.2, 'working', '1']],[['F27', 'Normal', [], ['free', '0'], 28016.537865230806, 'working', '1']]]

So my output should be:

[['99', 'Normal', [], ['busy', '0'], 362.01, 'working', '1']]

But I only get that the validation that says that the string doesn’t exist, when it obviously does. Here’s the code:

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

array = [[['99', 'Normal', [], ['busy', '0'], 28016.2, 'working', '1']],[['F27', 'Normal', [], ['free', '0'], 28016.537865230806, 'working', '1']]]

def searchBusyWorkers(array):
    busy = []
    for x in array:
        if 'busy' in x:
            ind = x.index('busy')
            busy.append(array[ind])
            return busy
        else:
            return "No workers have that condition."

>Solution :

Try This

word = 'busy'
array = [[['99', 'Normal', [], ['busy', '0'], 28016.2, 'working', '1']],
[['F27', 'Normal', [], ['free', '0'], 28016.537865230806, 'working', '1']]]


def searchBusyWorkers(array,word):
    out = []
    for a in array:
        for i in a:
            for x in i:
                try:
                    if word in x:
                        out.append(i)
                except TypeError:
                    if word == x:
                        out.append(i)
    if out:
        return out
    return "No workers have that condition."

print(searchBusyWorkers(array,word))

OUTPUT

[['99', 'Normal', [], ['busy', '0'], 28016.2, 'working', '1']]
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