首页 > 解决方案 > Separating nested for loops in list comprehensions

问题描述

Starting from this dataframe

import pandas as pd
df2 = pd.DataFrame({'t': ['a', 'a', 'a', 'b', 'b', 'b'],
                    'x': [1.1, 2.2, 3.3, 1.1, 2.2, 3.3],
                    'y': [1.0, 2.0, 3.0, 2.0, 3.0, 4.0]})

it's possible to simplify these nested for loops:

for t, df in df2.groupby('t'):
    print("t:", t)
    for d in df.to_dict(orient='records'):
        print({'x': d['x'], 'y': d['y']})

by separating the inner loop into a function:

def handle(df):
    for d in df.to_dict(orient='records'):    
        print({'x': d['x'], 'y': d['y']})

for t, df in df2.groupby('t'):
    print("t:", t)
    handle(df)

How might I similarly separate a nested list comprehension :

mydict = {
    t: [{'x': d['x'], 'y': d['y']} for d in df.to_dict(orient='records')]
       for t, df in df2.groupby(['t'])
}

into two separate loops?

I'm asking the question with just two levels of nesting, yet with just two nested loops the need is hardly critical. The motivations are:

标签: pythonlist-comprehension

解决方案


推荐阅读