将列表划分为对角线?

时间:2014-08-14 02:45:47

标签: python arrays list matrix diagonal

如果我有这份清单清单:

l = [
['a','r','v','s','s','t','n','g'],
['e','x','a','m','p','l','e','t'],
['g','z','n','p','u','t','x','m'],
['v','a','h','g','i','k','t','f']
]

如何根据对角线轻松将其划分为列表列表?

我想要的结果非常多:

[
['a'],
['r','e'],
['v','x','g',],
['s','a','z','v'],
['s','m','n','a'],

依旧......

我还应该提一下,我已经安装了numpy,无论如何都有帮助。

3 个答案:

答案 0 :(得分:3)

[ [ v[d-i] for i,v in enumerate(l) if d-i>=0 ] for d in xrange(len(l[0])) ]

开发这个阶段是:

[ <one-diagonal-row> for <index d of each element of first row of input> ]

[ [<element-of-diagonal d> for <each v, which is row i of l>] for d in xrange(len(l[0])) ]

[ [ v[d-i] for i,v in enumerate(l) <only if element exists>] for d in xrange(len(l[0])) ]

将您带到顶部的表达式。

答案 1 :(得分:2)

这是您理解的最明确的方式:

lists = [
['a','r','v','s','s','t','n','g'],
['e','x','a','m','p','l','e','t'],
['g','z','n','p','u','t','x','m'],
['v','a','h','g','i','k','t','f']
]

diagonals = []
for i in range( len(lists[0])+len(lists) - 1):
    diagonal = []

    for lst in lists:
        if len(lst)>i and i>=0:                 
            diagonal.append(lst[i])     
        i-=1

    diagonals.append(diagonal)

for lst in diagonals:
    print(lst)

diagonals = [
['a'],
['r', 'e'],
['v', 'x', 'g'],
['s', 'a', 'z', 'v'],
['s', 'm', 'n', 'a'],
['t', 'p', 'p', 'h'],
['n', 'l', 'u', 'g'],
['g', 'e', 't', 'i'],
['t', 'x', 'k'],
['m', 't'],
['f']
]

答案 2 :(得分:1)

你可以利用每个对角线的指数总和为给定整数的事实来实现这一点。

给定一个列表lst,我们有:

diagonals = [[''.join(c for j,c in enumerate(s) if i+j == n)
              for i,s in enumerate(lst)]
             for n in range(len(lst[0]))]

或者在这个特定的例子中:

In [15]: lst = ['arvsstng', 'examplet', 'gznputxm', 'vahgiktf']
In [16]: [[''.join(c for j,c in enumerate(s) if i+j == n) for i,s in enumerate(lst)] for n in range(len(lst[0]))]
Out[16]: 
[['a', '', '', ''],
 ['r', 'e', '', ''],
 ['v', 'x', 'g', ''],
 ['s', 'a', 'z', 'v'],
 ['s', 'm', 'n', 'a'],
 ['t', 'p', 'p', 'h'],
 ['n', 'l', 'u', 'g'],
 ['g', 'e', 't', 'i']]

如果你想在输出中有不同的长度列表,你可以在它上面运行一个过滤器:

In [18]: diagonals = [filter(None, sublst) for sublst in diagonals]

In [19]: diagonals
Out[19]: 
[['a'],
 ['r', 'e'],
 ['v', 'x', 'g'],
 ['s', 'a', 'z', 'v'],
 ['s', 'm', 'n', 'a'],
 ['t', 'p', 'p', 'h'],
 ['n', 'l', 'u', 'g'],
 ['g', 'e', 't', 'i']]