【问题标题】:retrieve the elements from a list-of-list data structure从列表数据结构中检索元素
【发布时间】:2021-04-15 04:57:58
【问题描述】:

我正在运行以下代码段

import numpy as np
np.random.seed(123)
from skopt.space import Space
from skopt.sampler import Lhs
space = Space([(0., 1.), (0., 1.),(0.,1.)])
lhs = Lhs(lhs_type="centered", criterion=None)
theta_design = lhs.generate(space.dimensions, 200)

生成的 theta_design 是一个长度为 200 的列表。每个列表元素也是一个长度为3 的列表。部分结果如下所示。所以 theta_design 是一种大小为200*3 的矩阵。我的问题是如何沿着这个列表结构的第一个维度检索元素。换句话说,我想从这个矩阵中检索前 100 个元素。

【问题讨论】:

  • 如果 theta_design 是 numpy 数组,则使用 numpy 的索引 theta_design[:100, 0] -> 这将为您提供前 10000 行并获取每行中第一个元素的值。

标签: python python-3.x numpy scipy


【解决方案1】:
first_col, second_col, third_col = zip(*theta_design[:100])

【讨论】:

    【解决方案2】:

    我认为您想要获取前 100 个列表中每个列表的第一个元素,并将它们保存到一个列表中。 这可以通过list comprehension 来完成。

    first_element_of_each_list = [row[0] for row in theta_design[:100]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2016-03-14
      • 2022-09-26
      • 1970-01-01
      • 2020-04-19
      • 2012-03-16
      相关资源
      最近更新 更多