【问题标题】:How to set a matrice with a complex nested tupled list如何使用复杂的嵌套元组列表设置矩阵
【发布时间】:2014-02-07 18:20:20
【问题描述】:

我有一个看起来像这样的嵌套元组列表

nested_ls =   [[(0, (0, 0)), (1, (1, 1)), (2, (2, 2)), (1, (1, 3))], [(3, (3, 3)), (2, (2, 4)), (4, (4, 0)), (3, (3, 1))], [(3, (3, 5)), (2, (2, 6)), (3, (3, 7)), (3, (3, 8))]]

我希望用每个元组中的两个项目来设置矩阵“m”;第一项 item1 是外部元组中的每一项 [[(item1(0,0)), (item1(1,1)][ ....(item1(3,5))....] ..] 并且第二项 item2 在每个内部元组中的索引位置 [1] 上,例如 (3(3,item2))。

我尝试使用 groupby 迭代器循环如下:

from numpy  import *
from itertools import groupby
     for i,j in groupby(nested_ls, lambda x: x):
      for j in i:
          print j # item1 in outer tuple
          l = j[1] # inner tuple
          m[i,j] = i[j-1][1],i[j][1]] +=1 #matrice m, [j-1] is to get item1 in outer tuple
      return m                             
                                        # and i[j][1] is to get indexposition [1] in inner tuple

生成的矩阵应该类似于

[0 1 0 0 1]
[0 1 1 0 1]
[0 0 0 1 0]

其中每个 1 代表 item1*item2 在nested_ls 中的出现。

            inner tuple, item2
             0  1 2 3 4 5 6 7 8
   outer   0 [1 0 0 0 0 0 0 0 0]
   tuple   1 [0 1 0 1 0 0 0 0 0]
   item1   2 [0 0 1 0 0 0 1 0 0]
           3 [0 1 0 1 0 1 0 1 1]
           4 [0 0 0 0 1 0 0 0 0]

【问题讨论】:

  • 我不太明白。 (a, (b, c)) 在原始元组中的每个术语是什么意思?矩阵应该看起来像这样或完全一样?
  • 这些项目是数据集中令牌的 ID 号。我正在尝试使用每个元组中的 a 和 c 设置数组。对于每一次出现,它应该添加 +=1。绘制的结果矩阵不必与上面绘制的完全一样,它应该在矩阵中与嵌套列表中 a 和 c 共同出现的位置相对应的位置上显示 1 或至少 1。
  • 抱歉,这还不是 100% 清楚。 b 和 c 是索引吗? a 和 c 同时出现到底是什么意思?为什么您的列表包含两个列表,每个列表都包含元组,而不是简单地包含一个元组列表?这有意义吗?
  • 例如,在元组 (3(a), (3, 5(c))) 中,如果 a 的值为 3,c 的值为 5,则在元组中 +1矩阵,如果两次,即nested_ls包含(3(a), (3, 5(c)))(3(a), (3, 5(c))) 比2在矩阵中的列中,并且很快。如果 i[j-1][1],i[j][1]] 中的循环变量 i,j 设置正确,只是我不太确定如何定义它,则应该生成该变量。第一部分 i[j-1][1] 应该是矩阵中的行..
  • 和第 1 行,第二部分是 i[j][1] 应该是行中的第 1 列,[j-1] 应该从第 0 行而不是第 1 行开始循环,但它不适用于我上面制作的循环。

标签: for-loop numpy matrix group-by tuples


【解决方案1】:

听起来您想创建一个二维数组,其中每个 1 值对应于nested_ls 结构中给定的坐标。你可以用这样的代码做到这一点:

nested_ls =   [
[(0, (0, 0)), (1, (1, 1)), (2, (2, 2)), (1, (1, 3))],
[(3, (3, 3)), (2, (2, 4)), (4, (4, 0)), (3, (3, 1))],
[(3, (3, 5)), (2, (2, 6)), (3, (3, 7)), (3, (3, 8))]
]

#extract coordinates from nested structure
coordinates = [(a, c) for l in nested_ls for a, (b, c) in l]

#construct empty matrix.
width  = 1 + max(c for a,c in coordinates)
height = 1 + max(a for a,c in coordinates)
matrix = [[0 for x in range(width)] for y in range(height)]

#populate matrix
for a, c in coordinates:
    matrix[a][c] += 1

#display matrix
for row in matrix:
    print row

(抱歉,我使用的是普通列表而不是 numpy 矩阵 - 我没有安装该库。不过,我认为基本原理是相同的。)

结果:

[1, 0, 0, 0, 0, 0, 0, 0, 0]
[0, 1, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 1, 0, 1, 0, 1, 0, 0]
[0, 1, 0, 1, 0, 1, 0, 1, 1]
[1, 0, 0, 0, 0, 0, 0, 0, 0]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-28
    • 2021-11-17
    • 1970-01-01
    • 2013-09-08
    • 1970-01-01
    • 2020-05-28
    相关资源
    最近更新 更多