def split_data(): test_size = float(entry.get()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0) huafen=(f'X_train: {X_train}, X_test: {X_test}, y_train: {y_train}, y_test: {y_test}') a6=Text(root) a6.place(x=600, y=100,height=100,width=500) a6.insert(END, huafen) return X_train, X_test, y_train, y_test label=tk.Label(root, text='请输入测试集比例:') label.place(x=600,y=65) entry=tk.Entry(root) entry.place(x=700,y=65) button = tk.Button(root, text='划分数据集', command=split_data) button.place(x=850,y=65)怎么把 X_train, X_test, y_train, y_test拿到def外面使用
时间: 2023-12-24 19:14:24 浏览: 93
可以将函数的返回值赋值给全局变量,然后在需要使用的地方直接调用即可。例如:
```python
# 定义全局变量
global X_train, X_test, y_train, y_test
def split_data():
# 函数内部操作
# ...
# 将结果赋值给全局变量
global X_train, X_test, y_train, y_test
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0)
# ...
# 在需要使用的地方直接调用全局变量
print(X_train)
print(X_test)
print(y_train)
print(y_test)
```
相关问题
def split_data(): test_size = float(entry.get()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0) huafen=(f'X_train: {X_train}, X_test: {X_test}, y_train: {y_train}, y_test: {y_test}') a6=Text(root) a6.place(x=600, y=100,height=100,width=500) a6.insert(END, huafen)怎么把划分好的比例弄到函数外面
你可以将X_train、X_test、y_train、y_test作为函数的返回值,然后在函数外面接收这些返回值。具体代码如下所示:
```python
def split_data():
test_size = float(entry.get())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0)
return X_train, X_test, y_train, y_test
X_train, X_test, y_train, y_test = split_data()
huafen = f'X_train: {X_train}, X_test: {X_test}, y_train: {y_train}, y_test: {y_test}'
a6 = Text(root)
a6.place(x=600, y=100, height=100, width=500)
a6.insert(END, huafen)
```
这样,划分好的比例就可以在函数外面使用了。
def split_data(): global X_train, X_test, y_train, y_test test_size = float(entry.get()) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0) huafen=(f'X_train: {X_train}, X_test: {X_test}, y_train: {y_train}, y_test: {y_test}') a6=Text(root) a6.place(x=600, y=100,height=100,width=500) a6.insert(END, huafen)怎么让X_train, X_test, y_train, y_test 拿到def外面也能用
你可以将split_data函数的返回值设为X_train, X_test, y_train, y_test,然后在函数调用的地方将其保存到全局变量中,这样就可以在函数外部使用了。
例如:
```
def split_data():
test_size = float(entry.get())
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=0)
return X_train, X_test, y_train, y_test
X_train, X_test, y_train, y_test = split_data() # 在函数外部调用split_data函数并保存返回值到全局变量中
```
阅读全文