python - 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:
- By the time there are a few levels, the code becomes tough to read.
- Developing and testing smaller blocks guards against (present and future) mistakes at more than the outer level.
解决方案
推荐阅读
- botframework - 如何对齐具有相同宽度的 MS Teams 机器人消息
- android - 所有客户端解除绑定后,Android绑定服务未销毁
- bluetooth-lowenergy - bluenrg-1 是否支持语音控制?
- vue.js - 如何在 Vue3 中渲染多个插槽?
- oracle - oracle 中的 nvarchar 到日期转换不正确
- awk - 摆脱前 5 个字符,而不是第 32 个字符之后的所有其他字符?
- python - 将导入的 .py 文件的结果写入文本文件
- python - 图像上框架文本的坐标
- javascript - react-router 如何从数组生成路由?
- sql - 经纬度半径范围内的oracle搜索