Magnotta
Magnotta

Reputation: 941

how to convert following code snippet in list comprehension

I wrote one method with a nested loop but now I want to convert it into list comprehension, how to convert following code snippet in list comprehension

def A(results, required_result):
    """
    Args: 
         results (list) -- list of dicts
         required_result (str)
    Returns:
         list of strings and dict
         e.g.: ['a', {'key': 'value'}, 'b']
    """
    data = []
    for result in results:
        result = result[required_result].replace('\n', '').split('<br>')
        for res in result:
            if 'some_text' in res:
                carousel = create_carousel(res)
                data.append(carousel)
            else:
                data.append(res)
    return data

Upvotes: 0

Views: 108

Answers (2)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

Here you go

output = [
    create_carousel(res)  if 'some text' in res else res #Making the if-condition choice and creating the object or keeping the item in the list
    for item in results #Iterating on results
    for res in item[required_result].replace('\n', '').split('<br>') #Create the temporary list after replace and split, and iterating on it
]

Upvotes: 2

L3viathan
L3viathan

Reputation: 27283

I don't think this is more readable than the original, but here you go:

data = [
    create_carousel(res) if 'some_text' in res else res
    for result in results
    for res in result[required_result].replace('\n', '').split('<br>')
]

Upvotes: 3

Related Questions