比较字符串在Python中浮动 [英] Compare string to float in Python

查看:185
本文介绍了比较字符串在Python中浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python shell中试过这个功能。

 >>> a ='apple'
>>> b = 11.1
>>> a> b
True
>>> a
'apple'
>>> b> a
False

有人可以向我解释 a> ; b 是真的?当 a 是一个字符串,而 b 是float。

解决方案

不同类型的元素之间的顺序比较是Python 2.x中的一个设计错误,在Python 3中已经被移除(在运行时出现错误)。 b
$ b

在3.x之前修正它并不是一个选项,因为有很多现有的软件在异构容器上进行排序(版本3是第一个故意向后兼容的文件)。

在Python 2.x中,您可以比较< / > ,唯一例外的情况是明确禁止的复数。



不同类型比较的排序结果是任意的,但至少为Python解释器的一个给定的运行,参见 http://docs.python。 org / 2 / reference / expressions.html#not-in 。不同的非数字类型的值总是被认为是不同的。


I tried this in python shell

>>> a='apple'
>>> b=11.1
>>> a>b
True
>>> a
'apple'
>>> b>a
False

Can someone explain to me how a>b is True? When a is an string and b is float.

解决方案

Order comparison between elements of different types was a "design bug" in Python 2.x that has been removed in Python 3 (where you get a runtime error).

Correcting it wasn't an option before 3.x because of a lot of existing software that does sorting on heterogeneous containers (and version 3 is the first in which backward compatibility is intentionally broken).

In Python 2.x you can compare anything for </>, with the only exception of complex numbers where this is explicitly forbidden.

The ordering result of comparison of different types is arbitrary but fixed at least for a given run of the Python interpreter, see http://docs.python.org/2/reference/expressions.html#not-in . Values of different non-numeric types are always considered different.

这篇关于比较字符串在Python中浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆