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

在Python中从子列表中获取所有非None项的索引?,python,list,list-comprehension,Python,List,List Comprehension,根据标题,我有一个这样的嵌套列表(嵌套列表是固定长度的): 我想返回一个列表(项目数等于list1中的子列表的长度),其中子列表是没有作为第x项的行的索引,即: [[non-None ID indices], [non-None Name indices], [non-None Value indices]] 以list1为例,结果应该是: [[0, 1, 2, 3], [0, 1, 2, 3], [0, 2]] 我目前的做法是: indices = [[] for _ in range(l

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

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

[[non-None ID indices], [non-None Name indices], [non-None Value indices]]
list1
为例,结果应该是:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 2]]
我目前的做法是:

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)
…这是可行的,但可能很慢(列表的长度有几十万)

有没有更好/更有效的方法

编辑:

我已经将上述for循环重构为嵌套的列表理解(类似于SilentGhost的答案)。下一行给出了与my原始实现相同的结果,但运行速度快了大约10倍

[[i for i in range(len(list1)) if list1[i][j] is not None] for j in range(len(log[0]))]
在python-2.x中,可以使用
itertools.izip
而不是
zip
来避免生成中间列表

[[i for i in range(len(list1)) if list1[i] is not None] for _ in range(len(log[0]))]

上述内容似乎比我原来的帖子快了10倍左右。

此变体比@SilentGhost的变体慢3倍(在某些输入上)。您编辑的变体无效,因为
list1[i]
始终不是
None
,例如,
list1[0]
[1,“foo”,10]
(注意:
[None,None,None]不是None
).谢谢-我想我已经修好了。
import numpy as np

map(lambda a: np.not_equal(a, None).nonzero()[0], np.transpose(list1))
# -> [array([0, 1, 2, 3]), array([0, 1, 2, 3]), array([0, 2])]
[[i for i in range(len(list1)) if list1[i] is not None] for _ in range(len(log[0]))]
import numpy as np

map(lambda a: np.not_equal(a, None).nonzero()[0], np.transpose(list1))
# -> [array([0, 1, 2, 3]), array([0, 1, 2, 3]), array([0, 2])]