yuqli
yuqli

Reputation: 5161

python for loop after update step?

I copied this code from this website, and am just wondering about the grammar here? Why is the for loop under the 'i+1'?

# centroids[i] = [x, y]
centroids = {
    i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
    for i in range(k)
}

The code produce the following results:

>>> np.random.seed(200)
>>> k = 3
>>> # centroids[i] = [x, y]
... centroids = {
...     i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
...     for i in range(k)
... }
>>>     
... 
>>> centroids
{1: [26, 16], 2: [68, 42], 3: [55, 76]}

Upvotes: 2

Views: 399

Answers (1)

TerryA
TerryA

Reputation: 59984

It's a dictionary comprehension (similar to a list comprehension), but the brackets make it seem like it's a normal dictionary initialisation.

Imagine if the brackets were on the same line:

centroids = {i+1: [np.random.randint(0, 80), np.random.randint(0, 80)] for i in range(k)}

So it's just a more verbose way of saying:

centroids = {}
for i in range(k):
    centroids[i+1] = [np.random.randint(0, 80), np.random.randint(0, 80)]

Upvotes: 4

Related Questions