Как заменить true и false на 1 и 0 питон

от admin

Как преобразовать false в 0 и true в 1 в python

есть ли способ, чтобы преобразовать true типа unicode 1 и false типа unicode до 0 (в python)?

например: x == ‘true’ and type(x) == unicode

PS: Я не хочу использовать if-else.

10 ответов:

использовать int() на логическом тесте:

int() превращает логическое значение в 1 или 0 . Обратите внимание, что любое значение не равна ‘true’ в результате 0 возвращается.

супер просто:

Если B является логическим массивом, напишите

Это мой обычный трюк.

Если вам нужно преобразование общего назначения из строки, которая сама по себе не является bool, вам лучше написать процедуру, подобную описанной ниже. В соответствии с духом duck typing, я не молча передал ошибку, но преобразовал ее в соответствии с текущим сценарием.

вот еще одно решение вашей проблемы:

это работает, потому что сумма кодов ASCII ‘true’ — это 448 , который является четным, в то время как сумма кодов ASCII ‘false’ и 523 что странно.

самое смешное в этом решении то, что его результат довольно случайный, если вход не одним из ‘true’ или ‘false’ . Половину времени он будет возвращаться 0 , а другая половина 1 . Вариант используя encode вызовет ошибку кодирования, если вход не является ASCII (таким образом, увеличивая неопределенность поведения).

серьезно, я считаю самым читаемым,и быстрее, решение заключается в использовании if :

см. некоторые микробные метки:

обратите внимание, как if решение по крайней мере 2.5 x времени быстрее чем все другой решения. Это делает не имеет смысл поставить в качестве требования, чтобы избежать использования if s за исключением того, что это какая-то домашняя работа (в этом случае вы не должны были спрашивать об этом в первую очередь).

Python: Convert true to 1 and false to 0

Write a Python program to convert true to 1 and false to 0.

Sample Solution:-

Python Code:

Flowchart:

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Читать:
Include cmath c что это

Как заменить true и false на 1 и 0 питон

Hello = «Hello»
hello = «hello»
print(«Hello == hello: «, Hello == hello)
Hello == hello: False

Hello = «Hello»
hello = «hello»
Hello_there = «Hello»
print(«Hello == hello: «, Hello == hello)
print(«Hello == Hello_there», Hello == Hello_there)
Hello == hello: False
Hello == Hello_there: True

t = True
f = False
print(«t != f: «, t != f)
t != f: True

How to convert 'false' to 0 and 'true' to 1?

Is there a way to convert true of type unicode to 1 and false of type unicode to 0 (in Python)?

For example: x == ‘true’ and type(x) == unicode

PS: I don’t want to use if — else .

ZygD's user avatar

9 Answers 9

Use int() on a boolean test:

int() turns the boolean into 1 or 0 . Note that any value not equal to ‘true’ will result in 0 being returned.

If B is a Boolean array, write

(A bit code golfy.)

Peter Mortensen's user avatar

You can use x.astype(‘uint8’) where x is your Boolean array.

Peter Mortensen's user avatar

Here’s a yet another solution to your problem:

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 523 which is odd.

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

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

See some microbenchmarks:

Notice how the if solution is at least 2.5x times faster than all the other solutions. It does not make sense to put as a requirement to avoid using if s except if this is some kind of homework (in which case you shouldn’t have asked this in the first place).

Похожие статьи