Skip to content Skip to sidebar Skip to footer

What Does It Mean By Putting Two Variable In A For-in Loop In Python

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.

Solution 1:

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)
     ...:     
011012

If works for the same reason that:

In [174]: a,b = [10,12]

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.

Solution 2:

The below codes are cited from sklearn's manual.enter link description here

import numpy as np
from sklearn.model_selection import StratifiedShuffleSplit
X = np.array([[1, 2], [3, 4], [1, 2], [3, 4], [1, 2], [3, 4]])
y = np.array([0, 0, 0, 1, 1, 1])
sss = StratifiedShuffleSplit(n_splits=5, test_size=0.5, random_state=0)
sss.get_n_splits(X, y)
5
print(sss)
StratifiedShuffleSplit(n_splits=5, random_state=0, ...)
for train_index, test_index in sss.split(X, y):
    print("TRAIN:", train_index, "TEST:", test_index)
    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

TRAIN: [5 2 3] TEST: [4 1 0]TRAIN: [5 1 4] TEST: [0 2 3]TRAIN: [5 0 2] TEST: [4 3 1]TRAIN: [4 1 0] TEST: [2 3 5]TRAIN: [0 5 1] TEST: [3 4 2]

For loop runs n_splits times.

Post a Comment for "What Does It Mean By Putting Two Variable In A For-in Loop In Python"