how can i change the code, to make it more functional (change the for loop for the same result only to make it shorter in 2 sentences)?
"""
Simply return an array with the predicted languages.
"""
resultSet = []
inputdata = request.data
#print(inputdata)
inputdataparsed = json.loads(request.data)
array_of_sentences = inputdataparsed['inputdata']
for obj_in_array in array_of_sentences:
obj_in_array_tmp = obj_in_array
sentence = obj_in_array['TEXT']
obj_type = obj_in_array['TYPE']
obj_lang = obj_in_array['LANGUAGE']
prediction = detect(sentence)
result_to_safe = {"TEXT":sentence,
"TYPE": obj_type,
"LANGUAGE":obj_lang,
"PREDICTED_LANGUAGE": prediction}
resultSet.append(result_to_safe)
break
print(resultSet)
CodePudding user response:
Your code is fine, it could use a bit of cleaning but that's okay.
You can shorten your loop to:
def make_dict(sentence_dict):
return {
"TEXT": sentence_dict["TEXT"],
"TYPE": sentence_dict["TYPE"],
"LANGUAGE": sentence_dict["LANGUAGE"],
"PREDICTED_LANGUAGE": detect(sentence_dict["TEXT"])
}
result_set = [ make_dict(sentence_dict) for sentence_dict in array_of_sentences ]
You can make this more functional by mapping make_dict
over array_of_sentences
as follows:
result_set = list(map(make_dict, array_of_sentences))