python - 我不明白第二个支架是如何工作的

标签 python python-3.x numpy

这段代码用于通过按所属类别着色来绘制一系列数据。 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 只是评估为 FalseTrue,然后用于访问索引 01

>>> 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/

相关文章:

python - 用字符替换空格

python - 嵌套字典中的平均值

python - 带有 except block 的变量范围 : Difference between Python 2 and 3

python - 当我尝试为现有的 Pylons 应用提供服务时出现 PasteScript 错误

python - 使用 Python 3.6.1 在 Linux/Intel Xeon 上使用 "fork"上下文 block 进行多处理?

python - 显示字符串中的不可打印字符

python - 我的名字中有两个字母数量相等,如何打印这两个字母及其数量

python - 将回归扩展到 Matplotlib 中的数据之外

python - 使用 to_categorical 转换 np.array 时的内存问题

python - 如何在没有 for 循环 Python 的情况下获得相同的数组输出