for循环在下面的代码中做什么?

2024-03-29 10:10:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力学习scikit learn(sklearn)。下面是试图用statsmodels.api从虹膜数据集。 但是我不确定for循环是如何工作的,也不确定sci工具包中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]

Tags: thefromapiiristargetfornamessklearn
2条回答

这是一种列表理解

species = []

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

for从列iris.target中逐个获取值并赋值给x,然后它使用这个x从列iris.target_names中获取值并将这个值附加到列表`species。你知道吗

所以它将值target转换为值target_name

这在功能上等同于:

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

本质上,它是对iterable中的每个元素x应用一个函数,并从结果中创建一个列表。你知道吗

以这种方式对列表执行操作比前面提到的方法稍微快一点,而且可读性更高(在我看来)。你知道吗

相关问题 更多 >