Python:布尔值列表到二进制字符串 [英] Python: Boolean List to Binary String

查看:224
本文介绍了Python:布尔值列表到二进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python中将布尔值列表转换为二进制字符串的最快方法是什么?

What's the fastest way to convert a list of booleans into a binary string in python?

例如boolList2BinString([True,True,False])='0b110'.

e.g. boolList2BinString([True, True, False]) = '0b110'.

此外,我该如何将该二进制字符串转换为二进制文字?这是否比从布尔列表转换为二进制立即数要花费更多的时间?怎么会这样?

Also, how would I convert that binary string into the binary literal? Would this take more time than just converting from the boolean list to the binary literal immediatley? How would one do this?

例如boolList2Bin([True,True,False])= 0b110.

e.g. boolList2Bin([True, True, False]) = 0b110.

谢谢!

推荐答案

关于第一个问题,您可以使用条件表达式:

Regarding your first question, you can use a list comprehension* and a conditional expression:

>>> def boolList2BinString(lst):
...     return '0b' + ''.join(['1' if x else '0' for x in lst])
...
>>> boolList2BinString([True, True, False])
'0b110'
>>>


关于第二个,您不能将该二进制字符串转换为二进制文字".顾名思义,文学必须逐字输入:


Regarding your second, you cannot "convert that binary string into the binary literal". As their name suggests, literals must be literally typed out:

>>> x = 0b110
>>>

也许您是想将引号从输出中删除?如果是这样,请使用 print :

Perhaps you meant that you want the quotes removed from the output? If so, use print:

>>> def boolList2BinString(lst):
...     return '0b' + ''.join(['1' if x else '0' for x in lst])
...
>>> boolList2BinString([True, True, False])
'0b110'
>>> print(boolList2BinString([True, True, False]))
0b110
>>>


*注意::我故意选择对str.join使用列表推导而不是生成器表达式,因为前者是


*Note: I purposefully chose to use a list comprehension with str.join instead of a generator expression because the former is generally faster.

这篇关于Python:布尔值列表到二进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆