Getting indices of True values in a boolean list

前端 未结 7 1922
不思量自难忘°
不思量自难忘° 2020-12-07 11:52

I have a piece of my code where I\'m supposed to create a switchboard. I want to return a list of all the switches that are on. Here \"on\" will equal True and

7条回答
  •  天命终不由人
    2020-12-07 12:02

    You can use filter for it:

    filter(lambda x: self.states[x], range(len(self.states)))
    

    The range here enumerates elements of your list and since we want only those where self.states is True, we are applying a filter based on this condition.

    For Python > 3.0:

    list(filter(lambda x: self.states[x], range(len(self.states))))
    
    

提交回复
热议问题