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.