programing

'false'를 0으로, 'true'를 1로 변환하는 방법은 무엇입니까?

sourcejob 2023. 6. 28. 21:40
반응형

'false'를 0으로, 'true'를 1로 변환하는 방법은 무엇입니까?

변환할 수 있는 방법이 있습니까?true유형의unicode1까지false유형의unicode0(파이썬)으로?

예:x == 'true' and type(x) == unicode

나는 되고 싶다.x = 1

PS: 사용하고 싶지 않습니다.if-else.

사용하다int()부울 테스트:

x = int(x == 'true')

int()부울을 로 변환합니다.1또는0다음 과 동일하지 않은 값'true'결과적으로0반환되는

한다면B부울 배열입니다. 쓰기

B = B*1

(약간의 코드 골프.)

사용할 수 있습니다.x.astype('uint8')어디에x부울 배열입니다.

다음은 귀사의 문제에 대한 또 다른 해결책입니다.

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

이는 다음의 ASCII 코드의 합계 때문에 작동합니다.'true'이라448이는 짝수인 반면, ASCII 코드의 합은'false'이라523그것은 이상합니다.


이 솔루션의 재미있는 점은 입력이 다음 중 하나가 아닌 경우 결과가 상당히 무작위적이라는 것입니다.'true'또는'false'절반의 시간이 돌아올 것입니다.0나머지 절반1다음을 사용한 변형 모델encode입력이 ASCII가 아닌 경우 인코딩 오류가 발생합니다(따라서 동작의 정의되지 않음이 증가함).


진심으로, 저는 가장 읽기 쉽고 빠른 해결책이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배 더 빠릅니다.사용을 피하기 위한 요구 사항으로 지정하는 것은 말이 안 됩니다.ifs 이것이 일종의 숙제인 경우를 제외하고는 (처음부터 이것을 묻지 말았어야 했습니다.)

만약 당신이 그 자체가 부울이 아닌 문자열로부터 범용 변환이 필요하다면, 당신은 아래에 설명된 것과 유사한 루틴을 작성하는 것이 좋습니다.오리 타이핑 정신에 따라 묵묵히 오류를 넘기지 않고 현재 시나리오에 맞게 변환했습니다.

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

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

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

이제 x는 다음과 같은 경우 1을 포함합니다.x == 'true'그렇지 않으면 0.

참고:x == 'true'그러면 bool이 반환되고 0을 추가하면 int 값(bool 값이 True인 경우 1, 그렇지 않은 경우 0)으로 입력됩니다.

이 경우에만:

const a = true; const b = false;

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

언급URL : https://stackoverflow.com/questions/20840803/how-to-convert-false-to-0-and-true-to-1

반응형