这段代码用于通过按所属类别着色来绘制一系列数据。 X_train
是一个数组 (115,2)
而 Y_train
是另一个数组 (115,)
以及它们各自的范围值。我的问题是 [Y_train == i]
到底做了什么?
colors = ["red", "greenyellow", "blue"]
for i in range(len(colors)):
xs = X_train[:, 0][Y_train == i]
ys = X_train[:,1][Y_train == i]
plt.scatter(xs, ys, c = colors[i])
plt.legend(iris.target_names)
plt.xlabel("Sepal length")
plt.ylabel("Sepal width")
最佳答案
Python 中的 bool 值只是整数的子类。
Y_train == i
只是评估为 False
或 True
,然后用于访问索引 0
或 1
。
>>> a = ['this string is at index 0', 'this string is at index 1']
>>> a[True]
'this string is at index 1'
>>> a[False]
'this string is at index 0'
>>> a[1 + 2 == 3] # true
'this string is at index 1'
关于python - 我不明白第二个支架是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71905244/