在python中将两个变量放入forin循环意味着什么

2024-05-14 08:02:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems。在一个例子中,我在for循环中看到了这个语法。在

from sklearn.model_selection import StratifiedShuffleSplit

split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
for train_index, test_index in split.split(housing, housing["income_cat"]):
    strat_train_set = housing.loc[train_index]
    strat_test_set = housing.loc[test_index]

我打印了列车索引和测试索引,它们是一组索引。 这个for循环是什么意思?训练索引和测试索引有不同数量的元素,迭代是如何工作的? 此代码是否等同于以下代码?在

^{pr2}$

Tags: and代码testforindexontrainmachine
1条回答
网友
1楼 · 发布于 2024-05-14 08:02:43

下面是for循环中两个变量的简单情况:

In [173]: for a,b in [[0,1],[10,12]]:
     ...:     print(a,b)
     ...:     
0 1
10 12

如果工作的原因相同:

^{pr2}$

迭代返回某种类型的元组或列表,a,b in ...将这两个值解压到匹配数量的变量中。在

for i, v in enumerate(['a','b','c']):
    print(i,v)

是在循环中解包的另一个常见用法。在

相关问题 更多 >

    热门问题