Python:运行函数将值追加到空列表中时不返回任何值
这可能是一个非常基本的问题,但我还没有弄明白 我目前正在使用以下命令将值附加到空列表中Python:运行函数将值追加到空列表中时不返回任何值,python,pandas,loops,for-loop,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 ['ru
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)
不确定我是否以正确的方式处理此问题,因此任何建议都将不胜感激
最好的方法是,不要像调用或搜索字符串一样调用或搜索变量名
相反,使用字典来存储可变数量的变量
坏习惯
良好做法
嗯,这实际上应该是可行的,因为您正在传递一个非基本python类型作为函数中的引用。也许“组”键中没有任何值?如果x中的“shoes”在代码中的计算结果为False,则语句中的值为Falseshoes'是一个变量的名称,而不是一个字典键的名称。调用函数pd.DataFrames[shoes]不会导致传递字符串shoes,而是传递一个名为“shoes”的字典对象。shoes中也没有任何名为“group”的内容。您确实有一些名为“groups”的东西,但这不是同一个键。或者,更确切地说,您会这样做,但是pd.DataFrames是一个名称错误;您可能是指pd.DataFrame?对上面的组和数据框打字错误进行了编辑。if语句用于搜索数据框的名称是否包含鞋子、靴子或凉鞋,如果它确实包含其中任何一种,则将该数据框中的值附加到空列表中。在我的例子中,靴子和凉鞋的数据框是空的;我将这些列为如何使用代码的示例。如果有一个名为function的函数,它接受一个名为x的参数!这种命名毫无意义。这个函数在全局范围内修改列表,这使得理解它应该做什么变得更加困难。
# 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]