Pythonic list to bitflag mapping

Steven Bethard steven.bethard at gmail.com
Fri Nov 19 20:00:52 EST 2004


Ramon Felciano wrote:
> I have a list of integers that I'd like to convert to a bitflag or 1D
> matrix format:
> 
> a = [3,4,6]
> b = [0,0,0,1,1,0,1,0,0,0] # a 1 for each position in the a list
[snip]
> [1 if x in a else 0 for x in range(10)]

How about:

 >>> a = [3,4,6]
 >>> [int(x in a) for x in range(10)]
[0, 0, 0, 1, 1, 0, 1, 0, 0, 0]

The idea here is to treat the bool 'x in a' as an int, making use of the 
fact that int(True) == 1 and int(False) == 0.

Steve



More information about the Python-list mailing list