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]}
i+1justiand change the range torange(1, k+1).i+1is made in each iteration of the loop where only a single addition operation is needed to adjust the range so that it yields the target keys for the dict. If only one argument is provided torange, the start of the range defaults to0. So essentially, since there is nostartorstepargument torange, all thei+1code is doing is keying each integer in the range to be the next iteration'sivalue (and k in final iteration whereiisk - 1). See range for more info.