将两个变量放在python中的for-in循环中是什么意思 [英] what does it mean by putting two variable in a for-in loop in python
问题描述
我正在阅读动手学习机器Scikit-Learn和TensorFlow:构建智能系统的概念,工具和技术.在一个示例中,我在for循环中看到了这种语法.
I am reading Hands-On Machine Learning with Scikit-Learn and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems. In an example, I see this syntax in for loop.
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]
我打印出train_index和test_index,它们是索引数组. 这个for循环是什么意思? train_index和test_index具有不同数量的元素,迭代如何工作? 这段代码是否等同于下面的代码?
I printed out the train_index and test_index, they are array of indices. What does this for loop mean? The train_index and test_index have different number of elements, how does iteration work? Is this code equivalent to the below?
from sklearn.model_selection import StratifiedShuffleSplit
split = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)
train_index, test_index = split.split(housing, housing["income_cat"]):
strat_train_set = housing.loc[train_index]
strat_test_set = housing.loc[test_index]
推荐答案
下面是一个简单的for循环中包含2个变量的情况:
Here's a simple case of 2 variables in a for loop:
In [173]: for a,b in [[0,1],[10,12]]:
...: print(a,b)
...:
0 1
10 12
如果出于以下原因而工作:
If works for the same reason that:
In [174]: a,b = [10,12]
迭代返回某种元组或列表,并且a,b in ...
将2个值解压缩到匹配数量的变量中.
The iteration returns some sort of tuple or list, and the a,b in ...
unpacks the 2 values into the the matching number of variables.
for i, v in enumerate(['a','b','c']):
print(i,v)
是循环解包的另一种常见用法.
is another common use of unpacking in a loop.
这篇关于将两个变量放在python中的for-in循环中是什么意思的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!