Python Question

get linear indexing for filtered sublist items

rather specific question that is hard to google/search. Suppose I have a list of lists:

lists = [[30,34,0,0],[455,0,0],[0,509,0,0,0,0,444]]


how can I return a list of lists with the following sequential operations:


  • remove zero entries

  • linearly index remaining entries



expected output:

[[0,1],[2],[3,4]]


The first part is easy enough to obtain with a list comprehension:

lists_no_zeros = [[value for value in row if value != 0] for row in lists]


Surely some combination of list comprehensions, zip, enumerate should do the trick..

Answer Source

You are half way there. You can use itertools.count() to get the indexes:

>>> from itertools import count
>>> c = count()
>>> lists = [[30,34,0,0],[455,0,0],[0,509,0,0,0,0,444]]
>>> [[next(c) for value in sublist if value] for sublist in lists]
[[0, 1], [2], [3, 4]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download