Как заменить true и false на 1 и 0 питон
Перейти к содержимому

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

  • автор:

Преобразование типов данных

При работе с данными используется самые различные типы. Но чтобы провести операцию над двумя разными типами, надо преобразовать одно из них в другое.

Неявные преобразования

Неявные преобразования происходят тогда, когда Python может автоматически привести один тип к другому. Например, рассмотрим выражение, где у нас один операнд принадлежит типу int , а второй float :

В данном примере мы пытаемся сложить два операнда тип int и str , но получаем ошибку в итоге. Для правильного результата надо преобразовать «6» с помощью встроенной int() в целое число.

Явные преобразования

Явные преобразования необходимы, когда Python автоматически не приводит один тип к другому. Например:

  • str() : преобразует значение в строку;
  • int() : преобразует значение в целое число;
  • float() : преобразует значение в число с плавающей запятой;
  • complex() : преобразует значение в комплексное число;
  • bool() : преобразует значение в булево значение;
  • list() : преобразует итерируемый объект в список;
  • tuple() : преобразует итерируемый объект в кортеж;
  • set() , frozenset() : преобразует итерируемый объект в изменяемое/неизменяемое множество;
  • bytes() , bytearray() : преобразует значение к бинарному типу/массиву.

Примеры

Для приведения других типов данных к булеву используется функция bool() , работающая по следующим соглашениям:

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

Python | Ways to convert Boolean values to integer

Given a boolean value(s), write a Python program to convert them into an integer value or list respectively. Given below are a few methods to solve the above task.

Convert Boolean values to integers using int()

Converting bool to an integer using Python typecasting.

Python3

Output:

Time Complexity: O(1)

Auxiliary Space: O(1)

Convert Boolean values to integers using the Naive Approach

Converting bool to an integer using Python loop.

Python3

Output:

Convert Boolean values to integers using NumPy

In the case where a boolean list is present.

Python3

Output:

Convert Boolean values to integers using map()

In a case where a boolean list is present.

Python3

Output:

Using List comprehension

This approach uses list comprehension to iterate through the list ‘bool_val’ and applies the int() function to each element, which converts the Boolean value to its integer equivalent (1 for True and 0 for False).

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:

Flowchart: Convert true to 1 and false to 0.

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Find the most frequent element in a list:

  • Weekly Trends

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *