[英]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
我不認為這比原始內容更具可讀性,但是您可以:
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>')
]
干得好
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
]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.