如何查找Python中为空的列表的所有索引

时间:2013-11-12 00:17:24

标签: python list iterator enumeration

我想知道是否有一种简单的方法可以找到列表中所有空的索引。

mylist  = [ [1,2,3,4], [] , [1,2,3,4] , [] ]

next((i for i, j in enumerate(mylist) if not j),"no empty indexes found")将返回列表的第一个空索引,但是我可以返回所有索引吗?如果没有空索引,它将默认为字符串"no empty indexes found"

我想将所有空索引附加到另一个列表中使用。

my_indexes_list.append(next((i for i, j in enumerate(self.list_of_colors) if not j),5))

3 个答案:

答案 0 :(得分:3)

在布尔上下文中使用空序列为假的事实,以及列表推导:

>>> mylist  = [[1,2,3,4], [] , [1,2,3,4] , []]
>>> [i for i,x in enumerate(mylist) if not x]
[1, 3]

答案 1 :(得分:1)

>>> [i for i,x in enumerate(mylist) if x ==[] ]
[1, 3]

答案 2 :(得分:-1)

empties[]
for s in mylist:
    is len(s) == 0
        empties.append(mylist.index(s))
相关问题