Elegant way to convert list to sixth line

I have a long list that looks like this:

[True, True, True, False, ... ] 

Representation of walls in a tile map. It is not guaranteed that it will be a multiple of 4 long, but it does not matter whether it will be supplemented at the end.

I would like to convert this to a hexadecimal string, so in the example above it will start with E ...

I was hoping there was a nice elegant way to do this (using Python 2.7.3)!

Thanks.

edited

This is an example of a 9x9 card:

 map = [True, True, True, True, True, True, True, True, True, True, True, True, True, False, False, True, True, True, True, True, True, False, False, False, False, True, True, True, True, True, False, False, False, False, True, True, True, True, True, True, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]# False, False, False padded 

I would like to be able

 str = heximify(map) print str > FFF9F87C3F3FFFFFFFFF8 
+4
source share
4 answers

Joining a single-layer club through bit manipulation, which seems more appropriate.

 val = hex(reduce(lambda total, wall: total << 1 | wall, walls, 0)) 

This does the same as:

 val = 0 for wall in walls: val <<= 1 # add one 0 bit at the "end" val |= wall # set this bit to 1 if wall is True, otherwise leave it at 0 val = hex(val) # get a hex string in the end val = format(val, 'x') # or without the leading 0x if it undesired 
+7
source
 >>> walls = [True, True, True, False] >>> hex(int(''.join([str(int(b)) for b in walls]), 2)) '0xe' 

or (based on @millimoose answer),

 >>> hex(sum(b<<i for i,b in enumerate(reversed(walls)))) '0xe' 
+4
source
 walls = [True, True, True, False, ... ] val = 0 for w in walls: val *= 16 val += int(w) val = hex(val) 

or dirty single line:

 val = hex(sum(i*16**pow for i,pow in zip((int(w) for w in walls),range(len(walls))[::-1]))) 
+2
source
 >>> hex(int("".join(["%d"%s for s in [True,True,True,False]]),2)) '0xe' 
0
source

Source: https://habr.com/ru/post/1492160/


All Articles