【问题标题】:Issues with indexing in python [closed]python中的索引问题[关闭]
【发布时间】:2013-10-29 08:21:29
【问题描述】:

我在 python 中有一个列表 A,其中包含一些数字,如 [1,4 ,10]。我有另一个矩阵,由 10 列和一些行组成,第一列是数字,如 [1 1 1 2 2 2 2 2 3 3 4 4 4 4 5 .... 等等。现在我想从另一个数组中检索这些行,该数组的第一列由列表 A 中的数字组成。我该如何在 python 中做到这一点?

【问题讨论】:

  • “数组”是什么意思(可能是另一个列表)?什么是“列”?你的“数组”是嵌套的吗?请显示一些代码。
  • @Hyperboreus。我已经更新了这个问题。我在原文中犯了一个错误。我应该说矩阵,
  • matrix 不是 Python 中的内置类型。你在使用numpy 库吗?或者你只是有一个列表列表,比如[[1,2],[3,4]]
  • @DSM 实际上是 numpy.ndarray

标签: python list numpy multidimensional-array


【解决方案1】:

如果您指的是 m[x + y * width] 中的矩阵,那么您可以使用 slice 检索行 X

例如:

row_index = 5
column_count = 10
start = row_index * column_count
end = start + column_count
row = m[start:end]

然后做你想做的事

rows = []
for index in list_A:
    rows.append(list_A[index * 10:index * 10 + 10])

如果您正在谈论检索列,那么就像这样

columns = []
for index in list_A:
    columns.append(list_A[index:len(list_A):10])

【讨论】:

    【解决方案2】:

    这个怎么样:

    target_list = [1, 4, 10]
    
    a = np.array([[1,0],
                  [5,0],
                  [10,0],
                  [4,0],
                  [1,0],
                  [7,0]])
    
    first_col = a[:,0]
    
    # create a boolean array
    to_retrieve = np.in1d(first_col, target_list)
    
    result = a[to_retrieve]
    

    结果:

    >>> result # retrieved rows whose first column elements are in the target list
    array([[ 1,  0],
           [10,  0],
           [ 4,  0],
           [ 1,  0]])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-30
      • 1970-01-01
      相关资源
      最近更新 更多