python - 将列表转换为十六进制字符串的优雅方式

标签 python

<分区>

我有一个看起来像这样的长列表:

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

代表瓦片 map 中的墙壁。不能保证它的长度是 4 的倍数,但它是否在最后被填充并不重要。

我想将其转换为十六进制字符串,因此对于上面的示例,它将以 E ... 开头

我希望有一种优雅的方式来做到这一点(使用 Python 2.7.3)!

谢谢。

已编辑

这是一个 9x9 map 的示例:

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

我想要的是能够

str = heximify(map)
print str
> FFF9F87C3F3FFFFFFFFF8

最佳答案

加入单线俱乐部,通过位操作的方式似乎更合适。

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

这与:

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's undesired

关于python - 将列表转换为十六进制字符串的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731822/

相关文章:

Python:杀死 child 的子进程

java Communications link failure 最后一个数据包成功发送到服务器

python - 用另一个数据帧中的 id 替换数据帧多列

python - 如何运行并行线程以在视频流的每一帧上应用函数?

python - Django Rest 显示 TemplateDoesNotExist

python - 根据条件填充数据框行的值

python - StopIteration在运行代码时不断显示随机

python - 如何在 Pandas 中按年和月加入 2 个数据框?

python - SQLAlchemy,如何将混合表达式设置为 'understand' 日期时间?

python - Unicode 大小写转换