Pythonic list to bitflag mapping

Bengt Richter bokr at oz.net
Sat Nov 20 02:54:24 EST 2004


On Fri, 19 Nov 2004 21:05:04 -0600, Terry Hancock <hancock at anansispaceworks.com> wrote:

>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)]
>
Or, since

 >>> issubclass(bool, int)
 True

then

 >>> a = [3 ,4 ,6]
 >>> [x in a for x in xrange(10)]
 [False, False, False, True, True, False, True, False, False, False]

Is easily converted:
 >>> [int(x in a) for x in xrange(10)]
 [0, 0, 0, 1, 1, 0, 1, 0, 0, 0]

Or can be used directly as an integer index to get a character

 >>> ['01'[x in a] for x in xrange(10)]
 ['0', '0', '0', '1', '1', '0', '1', '0', '0', '0']

for whatever...
 >>> ''.join(['01'[x in a] for x in xrange(10)])
 '0001101000'

etc.

Regards,
Bengt Richter



More information about the Python-list mailing list