Pythonic list to bitflag mapping

Terry Hancock hancock at anansispaceworks.com
Fri Nov 19 22:05:04 EST 2004


On Friday 19 November 2004 06:47 pm, Ramon Felciano wrote:
> a = [3,4,6]
> b = [0,0,0,1,1,0,1,0,0,0] # a 1 for each position in the a list
[...] 
> I can do this with loops etc, but was curious if there isn't a python
> one-liner or list comprehension way of doing it. What I'd like to
> write is something like the following:
> 
> [1 if x in a else 0 for x in range(10)]

[x in a for x in range(10)]

Though this will return boolean True/False values in Python 2.3+ and
an int in earlier versions.  However conditional operations will work
on either, so your code may tolerate this.

If you must have 0 and 1 though, you can use:

[(x in a and 1 or 0) for x in range(10)]

Cheers,
Terry

--
Terry Hancock ( hancock at anansispaceworks.com )
Anansi Spaceworks  http://www.anansispaceworks.com




More information about the Python-list mailing list