gpt4 book ai didi

更新步骤后的python for循环?

转载 作者:行者123 更新时间:2023-11-28 21:39:02 26 4
gpt4 key购买 nike

我从 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]}

最佳答案

这是一个字典理解(类似于列表理解),但是括号让它看起来像是一个普通的字典初始化。

想象一下,如果括号在同一行:

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)]

关于更新步骤后的python for循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47342373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com