【发布时间】:2014-01-17 09:55:03
【问题描述】:
有没有办法将unicode 类型的true 转换为1,将unicode 类型的false 转换为0(在Python 中)?
例如:x == 'true' and type(x) == unicode
我想要x = 1
PS:我不想用if-else。
【问题讨论】:
有没有办法将unicode 类型的true 转换为1,将unicode 类型的false 转换为0(在Python 中)?
例如:x == 'true' and type(x) == unicode
我想要x = 1
PS:我不想用if-else。
【问题讨论】:
在布尔测试中使用int():
x = int(x == 'true')
int() 将布尔值转换为1 或0。请注意,任何不等于'true'的值都将导致0被返回。
【讨论】:
str 类型的行为。
u'true' == 'true' 中,函数的行为与输入类型无关 [在 str 和 unicode 之间]。
arrayvalue == 'true' 比较的期望,我在这里回答的问题是特定于字符串(unicode)值的。
如果B是一个布尔数组,写
B = B*1
(有点代码高尔夫球。)
【讨论】:
numpy.multiply(B,1) 可以。
B=map(int,B) 在 python 3 中为我返回了一个地图对象。
您可以使用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
之所以有效,是因为'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.5x 倍快 比所有 其他解决方案. 不要求避免使用ifs 是有意义的,除非这是某种家庭作业(在这种情况下,您一开始就不应该问这个问题)。
【讨论】:
def intcast(v, _int=int): return _int(v == "true")。但是,它不会完全胜过条件表达式。
def setcontains(v, _s=frozenset(('true',))): return v in _s,几乎一样快。
如果您需要从本身不是布尔值的字符串进行通用转换,您最好编写一个类似于下面描述的例程。为了与鸭子打字的精神保持一致,我没有默默地传递错误,而是将其转换为适合当前场景。
>>> 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
【讨论】:
TypeError?如果 string 不包含 'true' 或 'false' 这是一个 value 错误。如果输入不是字符串,您将得到(99.99% 的时间)AttributeError,因此捕获ValueError 并将其重新提升为TypeError 是没有用的。
index引发AttributeError的例子吗?
return ['false', 'true'].index(s) except (ValueError, AttributeError)。
lower() 调用,因为这是进行此额外计算的唯一解决方案,并且将其包含在其中是不正确的微基准。当然,即使try...except 也需要一些时间,但如果没有引发异常(比如20ns 更少左右),差异就会很小。
+(False) 转换为 0 和
+(True) 转换为 1
【讨论】:
True/False 对象的,不是针对字符串的
以下任何一种都可以:
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 到 int:
x = (x == 'true') + 0
现在 x 包含 1 if x == 'true' else 0。
注意:x == 'true' 将返回 bool,然后在添加 0 时将其类型转换为具有值的 int(如果 bool 值为 True,则为 1,否则为 0)。
【讨论】:
只有这个:
常量 a = true; 常量 b = false;
console.log(+a);//1 console.log(+b);//0
【讨论】: