как преобразовать следующий фрагмент кода в понимание списка - PullRequest
0 голосов
/ 09 мая 2019

Я написал один метод с вложенным циклом, но теперь я хочу преобразовать его в понимание списка, как преобразовать следующий фрагмент кода в понимание списка

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

Ответы [ 2 ]

3 голосов
/ 09 мая 2019

Я не думаю, что это более читабельно, чем оригинал, но здесь вы идете:

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>')
]
2 голосов
/ 09 мая 2019

Вот, пожалуйста,

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
]
...