首页 > 解决方案 > 您如何将此循环编写为列表理解?

问题描述

我有这个代码

lista = list()
for dict_genres in df['genres']:
    suport = list()
    for genres in dict_genres:
        suport.append(genres['id'])
    lista.append(suport)

您如何将其写为列表理解?

标签: python

解决方案


具有 1 级列表理解

lista = []
for dict_genres in df['genres']:
    lista.append([genres['id'] for genres in dict_genres])

具有 2 级列表理解

lista = [
    [genres['id'] for genres in dict_genres]
    for dict_genres in df['genres']
]

推荐阅读