如何将Python函数输出转换为列表、字典或DataFrame以复用?
解决方法
你的test()函数目前只是直接打印结果,没有返回任何数据,这是你无法将结果转换为列表/字典/DataFrame的核心原因。你需要修改函数,让它收集结果并返回,再根据后续需求转换成合适的格式。
1. 先收集为列表(最基础的方式)
修改函数,把每次的(j,i)存入一个列表,最后返回这个列表:
def test(): results = [] # 初始化空列表存结果 scope = range(10) scope2 = range(len(df1.columns)) for j in scope2: for i in scope: if df1.iloc[:,[j]].shift(i).loc[selected_week].item() > df1.iloc[:,[j]].shift(i+1).loc[selected_week].item(): continue # 原代码的i+1无实际作用,改用continue让循环继续 else: results.append((j, i)) # 把(j,i)元组加入列表 break return results # 返回结果列表
调用后即可得到结果列表:
result_list = test() # 输出示例:[(1,0), (2,3), (3,3), ...]
2. 转换为字典(按列索引j为键)
如果需要以列索引j为键、对应的测试结果i为值,可基于列表转换:
result_dict = {j: i for j, i in result_list} # 输出示例:{1:0, 2:3, 3:3, ...}
也可以直接在函数内构建字典:
def test(): results = {} scope = range(10) scope2 = range(len(df1.columns)) for j in scope2: for i in scope: if df1.iloc[:,[j]].shift(i).loc[selected_week].item() > df1.iloc[:,[j]].shift(i+1).loc[selected_week].item(): continue else: results[j] = i break return results
3. 转换为DataFrame(最优推荐,适合后续逻辑判断)
如果后续要做i>5这类逻辑筛选,DataFrame是最方便的格式,可以直接用布尔索引快速操作。基于列表转换:
import pandas as pd result_df = pd.DataFrame(result_list, columns=["列索引j", "测试结果i"])
之后就能轻松筛选符合条件的记录:
# 筛选测试结果i>5的行 filtered_df = result_df[result_df["测试结果i"] > 5] # 获取对应的列索引j列表 target_j = filtered_df["列索引j"].tolist()
也可以直接在函数内返回DataFrame:
def test(): results = [] scope = range(10) scope2 = range(len(df1.columns)) for j in scope2: for i in scope: if df1.iloc[:,[j]].shift(i).loc[selected_week].item() > df1.iloc[:,[j]].shift(i+1).loc[selected_week].item(): continue else: results.append({"列索引j": j, "测试结果i": i}) break return pd.DataFrame(results)
额外优化提示
- 原代码里的
i + 1没有实际作用(未赋值给变量),改用continue更符合逻辑,能让循环继续判断下一个i值。 - 可以用
df1.iloc[:,j]代替df1.iloc[:,[j]],前者直接返回Series,调用item()更高效,无需生成单列DataFrame。
内容的提问来源于stack exchange,提问作者ps2341
相关产品推荐
相关产品推荐

