【发布时间】:2025-11-25 05:00:01
【问题描述】:
每次我尝试使用列表理解创建嵌套列表时,最终都会让人头疼或出现错误。我有一个我正在使用的四个变量的转置数据框,每个变量有 9 列。例如:
Date0, Date1, Date2, Date3 ... Date 9
GMV0, GMV1, GMV2, GMV3 .... GMV9
Revenue0, Revenue1, Revenue2, Revenue3 .... Revenue9
我正在尝试为这些列中的每一列创建一个嵌套列表。所需列表如下:
[[Date0, GMV0, Revenue0], [Date1, GMV1, Revenue1], [Date2, GMV2, Revenue2] ... [Date9, GMV9, Revenue9]]
我目前可以使用
创建所需的列表date=[col for col in test.columns if 'Date' in col]
gmv=[col for col in test.columns if 'GMV' in col]
rev=[col for col in test.columns if 'Gross Revenue' in col]
vars=[[Date[i], gmv[i], rev[i]] for i in range(len(Date))]
但这效率很低,我很肯定这是一个单行代码。
有人可以帮助我正确理解列表(或者可能是其他特定于转置数据的方法)并帮助我理解它吗?
【问题讨论】: