【问题标题】:What does the for loop do in the following code?以下代码中的 for 循环有什么作用?
【发布时间】:2019-11-19 07:57:59
【问题描述】:

我正在尝试学习 scikit learn (sklearn)。以下是尝试从 iris 数据集中使用 statsmodels.api 创建数据框的代码的一部分。 但我不确定 for 循环是如何工作的,以及来自 sci-kit 的 iris.target_names[x]target 的数据类型。谁能解释一下?

from sklearn import datasets ## Get dataset from sklearn

## Import the dataset from sklearn.datasets
iris = datasets.load_iris()

## Create a data frame from the dictionary
species = [iris.target_names[x] for x in iris.target]

【问题讨论】:

标签: python scikit-learn


【解决方案1】:

这在功能上等同于以下内容:

species = []
for x in iris.target:
    species.append(iris.target_names[x])
本质上是它在迭代中的每个元素x上应用了一个函数,并在结果中创建列表。

以这种方式对列表执行操作比前面提到的方法稍快一些,并且更具可读性(在我看来)。

【讨论】:

    【解决方案2】:

    它是列表理解,它确实

    species = []
    
    for x in iris.target:
        val = iris.target_names[x]
        species.append(val)
    

    foriris.target 列中逐一获取值并分配给x,然后它使用此x 从列iris.target_names 中获取值并将此值附加到列表`species。

    因此它将值target 转换为值target_name

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2020-02-18
      • 2018-11-07
      • 1970-01-01
      • 2021-02-28
      • 2021-06-04
      相关资源
      最近更新 更多