使用Python,从包含列表元素的矩阵中提取和打印项目

时间:2012-03-14 14:51:27

标签: python list matrix

我有以下表格的列表矩阵。

[[[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
]

使用Python,我想通过从每个内部列表中提取一个项目来打印矩阵([f,g,h,c])。例如,从每个内部列表中提取c元素:

[[c,c,c,c,c,c],
 [c,c,c,c,c,c],
 [c,c,c,c,c,c],
 [c,c,c,c,c,c],
 [c,c,c,c,c,c]]

3 个答案:

答案 0 :(得分:2)

也许使用numpy?

>>>a = [[range(4) for _ in range(4)] for _ in range(4)]
>>>import numpy
>>>b = numpy.array(a)
>>>b
array([[[0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3]],

   [[0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3]],

   [[0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3]],

   [[0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3],
    [0, 1, 2, 3]]])
>>>a[:, :, -1]
array([[3, 3, 3, 3],
   [3, 3, 3, 3],
   [3, 3, 3, 3],
   [3, 3, 3, 3]])

答案 1 :(得分:2)

f,g,h,c = (1,2,3,4)

matrix = [
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
 [[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c],[f,g,h,c]],
]

import operator
print [map(operator.itemgetter(3), x) for x in matrix]

答案 2 :(得分:2)

print([[x[3] for x in y] for y in matrix])