从Python的子列表中获取所有非None项的索引?

Noa*_*oah 2 python list-comprehension list

根据标题,我有一个像这样的嵌套列表(嵌套列表是固定长度):

        # ID,  Name, Value
list1 = [[ 1, "foo",    10],
         [ 2, "bar",  None],
         [ 3, "fizz",   57],
         [ 4, "buzz", None]]
Run Code Online (Sandbox Code Playgroud)

我想返回一个列表(项目数等于子列表的长度list1),其中子列表是没有None作为其第X项的行的索引,即:

[[non-None ID indices], [non-None Name indices], [non-None Value indices]]
Run Code Online (Sandbox Code Playgroud)

list1结果为例,结果应为:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 2]]
Run Code Online (Sandbox Code Playgroud)

我目前的实施是:

indices = [[] for _ in range(len(list1[0]))]
for i, row in enumerate(list1):
    for j in range(len(row)):
        if not isinstance(row[j], types.NoneType):
            indices[j].append(i)
Run Code Online (Sandbox Code Playgroud)

...有效,但可能很慢(列表的长度为数十万).

有没有更好/更有效的方法来做到这一点?

编辑:

我已经将上面的for循环重构为嵌套列表推导(类似于SilentGhost的答案).以下行给出了与我原始实现相同的结果,但运行速度提高了大约10倍.

[[i for i in range(len(list1)) if list1[i][j] is not None] for j in range(len(log[0]))]
Run Code Online (Sandbox Code Playgroud)

Sil*_*ost 6

>>> [[i for i, j in enumerate(c) if j is not None] for c in zip(*list1)]
[[0, 1, 2, 3], [0, 1, 2, 3], [0, 2]]
Run Code Online (Sandbox Code Playgroud)

在python-2.x中你可以使用itertools.izip而不是zip避免生成中间列表.