【问题标题】:How does this code works ( for loop in python)? [duplicate]这段代码是如何工作的(python中的for循环)? [复制]
【发布时间】:2020-07-21 18:10:03
【问题描述】:

我正在参加一些 Kaggle 认证课程。在中级机器学习教程中,我碰到了这个 for 循环。我知道 for 循环是如何工作的,但是这个 for 循环是不同的。

# Get names of columns with missing values
cols_with_missing = [col for col in X_train.columns
                     if X_train[col].isnull().any()]

# Drop columns in training and validation data
reduced_X_train = X_train.drop(cols_with_missing, axis=1)
reduced_X_valid = X_valid.drop(cols_with_missing, axis=1)

你可以在 col_with_missing 变量中看到。

  1. for 循环在括号内做什么以及为什么在 for 语句之前调用 col

  2. 如果我们在 if 语句中调用 X_train[col] 数据,那么 reduced_X_valid 变量是如何工作的,因为它得到了错误的数据。

【问题讨论】:

  • 它被称为列表理解。

标签: python python-3.x python-2.7


【解决方案1】:

它被称为list comprehension。您迭代列表等数据结构,您可以修改它的所有元素,或根据指定条件选择它们。最基本的列表理解是这样的

a = [1, 2, 3, 4, 5]
b = [x for x in a] # [1, 2, 3, 4, 5]

我们可以添加条件

a = [1, 2, 3, 4, 5]
b = [x for x in a if x < 3] # [1, 2]

【讨论】:

  • @Ayush 另请注意,cols_with_missing 正在使用上述列表理解获取具有 Nan 或缺失值的列。而 reduce_X_train 删除了 cols_with_missing 选择的那些列。这解释了为什么 reduce_X_train 减少了列。最佳
  • 是的,我明白了,但为什么 reduce_x_valid 会经历相同的迭代。
猜你喜欢
  • 1970-01-01
  • 2014-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-31
  • 2015-10-25
  • 2018-01-16
相关资源
最近更新 更多