嗨,我有我的Python列表A,在列表c中,我仅扩展了两列,如何限制行,以便列表C仅包含第2行和第3行
期望值
[[2,1],
[3,0]]
有没有办法解决列表推导问题
A = [[0,1,4,5,3],
[1,0,2,5,4],
[4,2,0,1,5],
[1,3,1,0,3],
[3,4,5,3,0]]
c=[]
print ('Print A')
print('\n'.join([''.join(['{:4}'.format(item) for item in row]) for row in A]))
c.extend( [[x[1],x[3]] for x in A])
print ('Print c')
print('\n'.join([''.join(['{:4}'.format(item) for item in rrr]) for rrr in c]))
答案 0 :(得分:1)
是,选择所需的行/列索引:
A = [[0,1,4,5,3],
[1,0,2,5,4],
[4,2,0,1,5],
[1,3,1,0,3],
[3,4,5,3,0]]
rows = [2,3]
cols = [1,3]
C = [[A[i][j] for j in cols] for i in rows]
结果:
>>> C
[[2, 1], [3, 0]]
也许会稍好一点,因为它避免每次都计算A[i]
只是添加另一种理解以命名该行:
C = [[row[j] for j in cols] for row in (A[i] for i in rows)]
这是基本的python方法。如果您的矩阵和索引列表很大,我想numpy
解决方案会更快。