python - 对 Python 列表语法感到困惑

标签 python python-2.7 numpy scikit-learn

这是代码和相关文档( http://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_iris.html#sklearn.datasets.load_iris ),我对这一行感到困惑, data.target[[10, 25, 50]],困惑为什么使用双 [[]],如果有人能澄清,那就太好了。

from sklearn.datasets import load_iris
data = load_iris()
print data.target[[10, 25, 50]]
print list(data.target_names)

提前致谢, 林

最佳答案

您的困惑是可以理解的:无论如何,这都不是“标准”Python。

data.target 在这种情况下是 ndarray来自 numpy:

In [1]: from sklearn.datasets import load_iris
   ...: data = load_iris()
   ...: print data.target[[10, 25, 50]]
   ...: print list(data.target_names)
[0 0 1]
['setosa', 'versicolor', 'virginica']

In [2]: print type(data.target)
<type 'numpy.ndarray'>

numpy 的 ndarray 实现允许您通过提供所需项目的索引列表来创建新数组。例如:

In [13]: data.target
Out[13]:
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
       0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
       1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
       2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2])

In [14]: data.target[1]
Out[14]: 0

In [15]: data.target[[1,2,3]]
Out[15]: array([0, 0, 0])

In [16]: print type(data.target[[1,2,3]])
<type 'numpy.ndarray'>

它很可能通过overriding __getitem__来做到这一点.

有关详细信息,请参阅 Indexing在 NumPy 数组文档中:

关于python - 对 Python 列表语法感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39059714/

相关文章:

python - 如何获取最大操作的索引

python - 将 Numpy 数组从 (3, 2, 3) reshape 为 (3, 3, 2)

c++ - 如何在 boost.python 中转换 std::string* ?

python - 为什么 print 语句在 python 中产生没有任何标签的换行符?

python - 值错误 : The elements are 0-sized

基于 Python Rate Limit 类的 View Flask

python - Numpy append 和普通 append

python - 是否有 Python 库可以模拟来自不同地址的网络流量

python - 如何在 python 中找到函数对象的必需参数?

python - 使用启用的扩展启动 selenium chromedriver