compare two python strings that contain numbers(比较两个包含数字的python字符串)
问题描述
更新:我应该早点指定这个,但并不是所有的名字都是简单的浮点数.例如,其中一些以YT"为前缀".所以例如YT1.1.所以,你有同样的问题 YT1.9
UPDATE: I should have specified this sooner, but not all of the names are simply floats. For example, some of them are "prefixed" with "YT". So for example" YT1.1. so, you have the same problem YT1.9 < YT1.11 should be true. I'm really surprised that the string comparison fails....
你好,这应该是一个非常简单的问题,但我似乎找不到答案.我想按名称对一堆 XL 工作表进行排序.每个名称都是数字,但与教科书部分"的编号方式相同,这意味着第 4.11 节在 4.10 之后,而在 4.9 和 4.1 之后.我认为只需将这些数字作为字符串进行比较即可,但我得到以下信息:
hello, this should be a pretty simple question but I can't seem to find the answer. I'd like to sort a bunch of XL worksheets by name. Each of the names are numbers but in the same way that textbook "sections" are numbered, meaning section 4.11 comes after 4.10 which both come after 4.9 and 4.1. I thought simply comparing these numbers as string would do but I get the following:
>>> s1 = '4.11'
>>> s2 = '4.2'
>>> s1> s2
False
>>> n1 = 4.11
>>> n2 = 4.2
>>> n1 > n2
False
如何比较这两个值以使 4.11 大于 4.2?
how can I compare these two values such that 4.11 is greater than 4.2?
推荐答案
将名称转换为整数元组并比较元组:
Convert the names to tuples of integers and compare the tuples:
def splittedname(s):
return tuple(int(x) for x in s.split('.'))
splittedname(s1) > splittedname(s2)
更新:由于您的名称显然可以包含数字以外的其他字符,因此您需要检查 ValueError
并留下任何无法转换为整数的值不变:
Update: Since your names apparently can contain other characters than digits, you'll need to check for ValueError
and leave any values that can't be converted to ints unchanged:
import re
def tryint(x):
try:
return int(x)
except ValueError:
return x
def splittedname(s):
return tuple(tryint(x) for x in re.split('([0-9]+)', s))
要对名称列表进行排序,请使用 splittedname
作为 sorted
的关键函数:
To sort a list of names, use splittedname
as a key function to sorted
:
>>> names = ['YT4.11', '4.3', 'YT4.2', '4.10', 'PT2.19', 'PT2.9']
>>> sorted(names, key=splittedname)
['4.3', '4.10', 'PT2.9', 'PT2.19', 'YT4.2', 'YT4.11']
这篇关于比较两个包含数字的python字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:比较两个包含数字的python字符串


基础教程推荐
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01