Python:将值附加到空列表的运行函数不返回任何值

时间:2018-04-30 23:46:57

标签: python pandas loops for-loop

这可能是一个非常基本的问题,但我无法弄清楚这一点。

我目前正在使用以下内容将值附加到空列表

shoes = {'groups':['running','walking']}
df_shoes_group_names = pd.DataFrame(shoes)

shoes_group_name=[]

for type in df_shoes_group_names['groups']:
    shoes_group_name.append(type)

shoes_group_name
['running', 'walking']

我正在尝试使用for循环完成相同的操作,但是,当我执行循环时,列表​​将返回为空白

shoes_group_name=[]

def list_builder(dataframe_name):
    if 'shoes' in dataframe_name:
        for type in df_shoes_group_names['groups']:
            shoes_group_name.append(type)

list_builder(df_shoes_group_names)

shoes_group_name
[]

该功能的原因是最终我将拥有多个具有不同产品的DF,因此我想在函数中使用if语句来处理每个列表的创建

所以例如未来的例子可能如下所示:

df_shoes_group_names
df_boots_group_names
df_sandals_group_names

shoes_group_name=[]
boots_group_name=[]
sandals_group_name=[]


def list_builder(dataframe_name):
    if 'shoes' in dataframe_name:
        for type in df_shoes_group_names['groups']:
            shoes_group_name.append(type)
    elif 'boots' in dataframe_name:
        for type in df_boots_group_names['groups']:
            boots_group_name.append(type)
    elif 'sandals' in dataframe_name:
        for type in df_sandals_group_names['groups']:
            sandals_group_name.append(type)    

list_builder(df_shoes_group_names)
list_builder(df_boots_group_names)
list_builder(df_sandals_group_names)

不确定我是否正确接近这一点,所以任何建议都会受到赞赏。

最佳,

1 个答案:

答案 0 :(得分:1)

你应该从不调用或搜索变量名称,就好像它是一个字符串一样。

相反,使用字典存储可变数量的变量。

不良做法

# dataframes
df_shoes_group_names = pd.DataFrame(...)
df_boots_group_names = pd.DataFrame(...)
df_sandals_group_names = pd.DataFrame(...)

def foo(x):
    if shoes in df_shoes_group_names:  # <-- THIS WILL NOT WORK
        # do something with x

良好做法

# dataframes
df_shoes_group_names = pd.DataFrame(...)
df_boots_group_names = pd.DataFrame(...)
df_sandals_group_names = pd.DataFrame(...)

dfs = {'shoes': df_shoes_group_names,
       'boots': df_boots_group_names,
       'sandals': df_sandals_group_names}

def foo(key):
    if 'shoes' in key:  # <-- THIS WILL WORK
        # do something with dfs[key]