我从this网站复制了这段代码,我只想知道这里的语法吗?为什么for循环位于' i + 1'?
之下# centroids[i] = [x, y]
centroids = {
i+1: [np.random.randint(0, 80), np.random.randint(0, 80)]
for i in range(k)
}
代码产生以下结果:
>>> 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]}
答案 0 :(得分:4)
这是字典理解(类似于列表理解),但括号使它看起来像是正常的字典初始化。
想象一下,如果括号位于同一行:
centroids = {i+1: [np.random.randint(0, 80), np.random.randint(0, 80)] for i in range(k)}
所以这只是一种更冗长的说法:
centroids = {}
for i in range(k):
centroids[i+1] = [np.random.randint(0, 80), np.random.randint(0, 80)]
答案 1 :(得分:1)
构建带有生成器对象的字典。
标准字典如下所示:
dictionary = {1: 'hello', 2: 'what's going on', 3: 'etc}
在这种情况下,通过此示例更容易看到发生了什么:
dictionary = {i: [chr(i)] for i in range(10)}
使用键i
和值[chr(i)]
在词典中输入10个条目。
这与结构基本相同:
centroids = {i+1: [np.random.randint(0, 80), np.random.randint(0, 80)] for i in range(k)}
上面的代码与问题中的代码完全相同(重新格式化)。