我用嵌套循环编写了一个方法,但是现在我想将其转换为列表理解,如何在列表理解中转换以下代码段
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
答案 0 :(得分:3)
我不认为这比原始内容更具可读性,但是您可以:
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>')
]
答案 1 :(得分:2)
你在这里
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
]