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:
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']]