小编Noa*_*oah的帖子

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

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

        # 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 …
Run Code Online (Sandbox Code Playgroud)

python list-comprehension list

2
推荐指数
1
解决办法
3263
查看次数

从Python中的多个源列表理解?

是否可以用列表理解来替换以下内容?

res = []
for a, _, c in myList:
    for i in c:
        res.append((a, i))
Run Code Online (Sandbox Code Playgroud)

例如:

# Input
myList = [("Foo", None, [1, 2, 3]), ("Bar", None, ["i", "j"])]

# Output
res = [("Foo", 1), ("Foo", 2), ("Foo", 3), ("Bar", "i"), ("Bar", "j")]
Run Code Online (Sandbox Code Playgroud)

python list-comprehension list

0
推荐指数
1
解决办法
791
查看次数

标签 统计

list ×2

list-comprehension ×2

python ×2