如何将‘ false’转换为0,将‘ true’转换为1?

有没有一种方法可以将 unicode类型的 true转换为1,将 unicode类型的 false转换为0(在 Python 中) ?

例如: x == 'true' and type(x) == unicode

我要 x = 1

附注: 我不想使用 if-else

346655 次浏览

在布尔测试中使用 int():

x = int(x == 'true')

int()将布尔值转换为 10。请注意,任何值 没有等于 'true'将导致返回 0

如果您需要从本身不是 bool 的字符串进行通用转换,那么您最好编写一个类似于下面描述的例程。为了保持 Duck 键入的精神,我没有悄悄地传递错误,而是根据当前场景的需要对其进行了转换。

>>> def str2bool(st):
try:
return ['false', 'true'].index(st.lower())
except (ValueError, AttributeError):
raise ValueError('no Valid Conversion Possible')




>>> str2bool('garbaze')


Traceback (most recent call last):
File "<pyshell#106>", line 1, in <module>
str2bool('garbaze')
File "<pyshell#105>", line 5, in str2bool
raise TypeError('no Valid COnversion Possible')
TypeError: no Valid Conversion Possible
>>> str2bool('false')
0
>>> str2bool('True')
1

这里还有一个解决你问题的办法:

def to_bool(s):
return 1 - sum(map(ord, s)) % 2
# return 1 - sum(s.encode('ascii')) % 2  # Alternative for Python 3

它工作是因为 'true'的 ASCII 码之和是 448,它是偶数,而 'false'的 ASCII 码之和是 523,它是奇数。


有趣的是,这个解决方案的结果是相当随机的,如果输入是 没有'true''false'之一。一半的时间它会返回 0,另一半返回 1。如果输入不是 ASCII,使用 encode的变体将引发编码错误(从而增加了行为的未定义性)。


说真的,我认为最易读的 更快解决方案是使用 if:

def to_bool(s):
return 1 if s == 'true' else 0

查看一些微基准测试:

In [14]: def most_readable(s):
...:     return 1 if s == 'true' else 0


In [15]: def int_cast(s):
...:     return int(s == 'true')


In [16]: def str2bool(s):
...:     try:
...:         return ['false', 'true'].index(s)
...:     except (ValueError, AttributeError):
...:         raise ValueError()


In [17]: def str2bool2(s):
...:     try:
...:         return ('false', 'true').index(s)
...:     except (ValueError, AttributeError):
...:         raise ValueError()


In [18]: def to_bool(s):
...:     return 1 - sum(s.encode('ascii')) % 2


In [19]: %timeit most_readable('true')
10000000 loops, best of 3: 112 ns per loop


In [20]: %timeit most_readable('false')
10000000 loops, best of 3: 109 ns per loop


In [21]: %timeit int_cast('true')
1000000 loops, best of 3: 259 ns per loop


In [22]: %timeit int_cast('false')
1000000 loops, best of 3: 262 ns per loop


In [23]: %timeit str2bool('true')
1000000 loops, best of 3: 343 ns per loop


In [24]: %timeit str2bool('false')
1000000 loops, best of 3: 325 ns per loop


In [25]: %timeit str2bool2('true')
1000000 loops, best of 3: 295 ns per loop


In [26]: %timeit str2bool2('false')
1000000 loops, best of 3: 277 ns per loop


In [27]: %timeit to_bool('true')
1000000 loops, best of 3: 607 ns per loop


In [28]: %timeit to_bool('false')
1000000 loops, best of 3: 612 ns per loop

请注意,if解决方案是 至少 2.5倍乘以 再快点所有其他解决方案。把 没有作为一个避免使用 if的要求是有意义的,除非这是某种家庭作业(在这种情况下,你一开始就不应该问这个问题)。

如果 B是布尔数组,则写入

B = B*1

(比特码高尔夫)

Bool to int: x = (x == 'true') + 0

现在 x 包含1 if x == 'true' else 0。

注意: x == 'true'将返回 bool,当 bool 值为 True else 0时,它将被类型化为 int,值为(如果 bool 值为 True else 0,则为1)。

可以使用 x.astype('uint8'),其中 x是布尔数组。

只有这个:

Const a = true; Const b = false;

Log (+ a) ;//1 Log (+ b) ;//0

+(False)转换为0和 +(True)转换为1

以下任何一种方法都有效:

s = "true"


(s == 'true').real
1


(s == 'false').real
0


(s == 'true').conjugate()
1


(s == '').conjugate()
0


(s == 'true').__int__()
1


(s == 'opal').__int__()
0




def as_int(s):
return (s == 'true').__int__()


>>>> as_int('false')
0
>>>> as_int('true')
1