Python编程语言学习:利用locals函数判断某个变量参数之前是否已经被定义/存在/出现

Python编程语言学习:利用locals函数判断某个变量参数之前是否已经被定义/存在/出现


利用locals函数判断某个变量参数之前是否已经被定义/存在/出现

输出结果

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 768 entries, 0 to 767
Data columns (total 9 columns):
 #   Column                    Non-Null Count  Dtype
---  ------                    --------------  -----
 0   Pregnancies               768 non-null    int64
 1   Glucose                   768 non-null    int64
 2   BloodPressure             768 non-null    int64
 3   SkinThickness             768 non-null    int64
 4   Insulin                   768 non-null    int64
 5   BMI                       768 non-null    float64
 6   DiabetesPedigreeFunction  768 non-null    float64
 7   Age                       768 non-null    int64
 8   Outcome                   768 non-null    int64
dtypes: float64(2), int64(7)
memory usage: 54.1 KB
None
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', '__file__', '__cached__', 'plt', 'pd', 'data_frame', 'col_label', 'cols_other', 'data_X', 'data_y_label_μ'])
data_X
data_y_label_μ
data_dall02
data_dall02 not in locals().keys()!

实现代码

# Python编程语言学习:利用locals函数判断某个变量参数之前是否已经被定义/存在/出现
import pandas as pd

data_frame=pd.read_csv('data_csv_xls\diabetes\diabetes.csv')

col_label='Outcome'
cols_other=['Pregnancies','Glucose','BloodPressure','SkinThickness','BMI']
data_X=data_frame[cols_other]
data_y_label_μ=data_frame[col_label]

# 判断某个参数之前是否已经被定义/存在/出现
print(locals().keys())
param_lists=['data_X','data_y_label_μ','data_dall02']
for param in param_lists:
    print(param)
    if param not in locals().keys():
        print('%s not in locals().keys()!'%param)
(0)

相关推荐