Is there a Don't Care value for lists in Python

  • A+
Category:Languages

Is there a way to use count() where you are looking for a specific value in the nested list and not caring about the rest?

lst = [[1,6],[1,4],[3,4],[1,2]] X = 1 lst.count([X, _ ]) 

This would return a count of 3, since there are three nested lists that have a 1 in the first index.

Is there a way to do this?

 


Use some sneaky sum() hacks:

sum(k[0] == X for k in your_list) 

I.e.

>>> X = 1 >>> your_list = [[1,6],[1,4],[3,4],[1,2]] >>> sum(k[0] == X for k in your_list) 3 

why?

The section: k[0] == X for k in your_list is a generator expression that yields True for each element in your_list which has first element equal to your X. The sum() function takes the values and treats a True as a 1.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: