如何在 Python 中将“false”转换为 0 并将“true”转换为 1

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20840803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:21:00  来源:igfitidea点击:

How to convert ‘false’ to 0 and ‘true’ to 1 in Python

pythonstringint

提问by PythonEnthusiast

Is there a way to convert trueof type unicodeto 1 and falseof type unicodeto 0 (in Python)?

有没有办法将true类型转换unicode为 1 并将false类型转换unicode为 0(在 Python 中)?

For example: x == 'true' and type(x) == unicode

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

I want x = 1

我想要 x = 1

PS: I don't want to use if-else.

PS:我不想使用if- else

采纳答案by Martijn Pieters

Use int()on a boolean test:

用于int()布尔测试:

x = int(x == 'true')

int()turns the boolean into 1or 0. Note that any value notequal to 'true'will result in 0being returned.

int()将布尔值转换为1or 0。请注意,任何等于的值'true'都将导致0返回。

回答by Abhijit

If you need a general purpose conversion from a string which per se is not a bool, you should better write a routine similar to the one depicted below. In keeping with the spirit of duck typing, I have not silently passed the error but converted it as appropriate for the current scenario.

如果您需要从本身不是 bool 的字符串进行通用转换,您最好编写一个类似于下面描述的例程。本着鸭子打字的精神,我没有默默地传递错误,而是根据当前场景将其转换为适当的。

>>> 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

回答by Bakuriu

Here's a yet another solution to your problem:

这是您问题的另一种解决方案:

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

It works because the sum of the ASCII codes of 'true'is 448, which is even, while the sum of the ASCII codes of 'false'is 523which is odd.

它的工作原理因为ASCII码的总和'true'就是448,这是偶数,而的ASCII码的总和'false'就是523这是奇怪的。



The funny thing about this solution is that its result is pretty random if the input is notone of 'true'or 'false'. Half of the time it will return 0, and the other half 1. The variant using encodewill raise an encoding error if the input is not ASCII (thus increasing the undefined-ness of the behaviour).

这个解决方案的有趣之处在于,如果输入不是'true'or之一,它的结果是非常随机的'false'。一半的时间它会回来0,而另一半1encode如果输入不是 ASCII,则使用的变体将引发编码错误(从而增加行为的不确定性)。



Seriously, I believe the most readable, and faster, solution is to use an if:

说真的,我相信最易读、速度更快的解决方案是使用if

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

See some microbenchmarks:

查看一些微基准测试:

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

Notice how the ifsolution is at least2.5xtimes fasterthan allthe other solutions. It does notmake sense to put as a requirement to avoid using ifs except if this is some kind of homework (in which case you shouldn't have asked this in the first place).

请注意该if解决方案比所有其他解决方案至少2.5倍。要求避免使用s是没有意义的,除非这是某种作业(在这种情况下,您首先不应该问这个)。if

回答by Chipotle

If Bis a Boolean array, write

如果B是布尔数组,则写

B = B*1

(A bit code golfy.)

(有点代码高尔夫球。)

回答by M C Akash

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

布尔到整数: x = (x == 'true') + 0

Now the x contains 1 if x == 'true'else 0.

现在 x 包含 1,x == 'true'否则为 0。

Note: x == 'true'will return bool which then will be typecasted to int having value (1 if bool value is True else 0) when added with 0.

注意:x == 'true'将返回 bool 然后将其类型转换为具有值的 int(如果 bool 值为 True,则为 1,否则为 0)当加上 0 时。

回答by shahar_m

You can use x.astype('uint8')where xis your Boolean array.

您可以使用x.astype('uint8')wherex是您的布尔数组。

回答by Fernando Pascoal Gomes

only with this:

只有这样:

const a = true; const b = false;

const a = true; const b = 假;

console.log(+a);//1 console.log(+b);//0

console.log(+a);//1 console.log(+b);//0