python二进制字符串,Python:布尔值列表到二进制字符串

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

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?

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

Thanks!

解决方案

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

>>>

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

>>>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值