如何将包含不同数量项目的列表解压到各个变量中?

问题描述 投票:0回答:1
import streamlit as st

sidebar_counter = 9
# this number can vary depending on what is selected by the user

column_list = [col1, col2, col3, col4, col5]
# column_list can vary and be a list that is [col1, col5] and just two items depending on what is selected by the user

#my goal is to assign each col# to each column as follows:
col1, col2, col3, col4 = st.columns(sidebar_counter)

# where sidebar_counter will already include the number of columns selected.

有没有办法根据所选内容动态解压 col1、col2、col3?

我尝试过以下方法:

import streamlit as st

column_list = st.columns(sidebar_counter)

但是,这不起作用,因为当我调用任何列(例如 col1)时,它没有定义。

python variable-assignment streamlit iterable-unpacking
1个回答
0
投票

您可以在全局字典中设置变量,然后可以在脚本中调用该变量。例如:

for s in range(sidebar_counter):
    globals()[f"col{s+1}"] = column_list[s]

或者,您可以在本地字典中设置变量,然后将该变量调用到函数中。例如:

for s in range(sidebar_counter):
    locals()[f"col{s+1}"] = column_list[s]

但是,在我看来,最好的方法是将变量保存在常规字典中,然后您就可以使用该字典。

© www.soinside.com 2019 - 2024. All rights reserved.