60行Python代码轻松搞定数据库查询 1秒找到需要的数据( 四 )


60行Python代码轻松搞定数据库查询 1秒找到需要的数据

文章插图
 
2.2 快速表格渲染2.2.1 利用列表推导快速渲染静态表格
通过前面的内容,我们知晓了在Dash中如果渲染一张带有样式的静态表格,而日常需求中,面对批量的数据,我们当然不可能手动编写整张表对应的代码,对于数量较多的表格,我们可以配合Python中常用的列表推导来实现 。
比如下面的例子:
?
app4.py
?
import dashimport dash_html_components as htmlimport dash_bootstrap_components as dbcimport pandas as pdimport numpy as npfake_df = pd.DataFrame(np.random.rand(1000).reshape(200, 5))fake_df.rename(lambda s: f'字段{s}', axis=1, inplace=True) # 批量格式化列名app = dash.Dash(__name__)app.layout = html.Div(    dbc.Container(        dbc.Table(            [                html.Thead(                    html.Tr(                        [html.Th('行下标', style={'text-align': 'center'})] +                        [                            html.Th(column, style={'text-align': 'center'})                            for column in fake_df.columns                        ]                    )                ),                html.Tbody(                    [                        html.Tr(                            [html.Th(f'#{idx}', style={'text-align': 'center'})] +                            [                               html.Td(row[column], style={'text-align': 'center'})                                for column in fake_df.columns                            ]                        )                        for idx, row in fake_df.iterrows()                    ]                )            ],            striped=True,            bordered=True        ),        style={            'margin-top': '50px'  # 设置顶部留白区域高度        }    ))if __name__ == '__main__':    app.run_server(debug=True)


推荐阅读