比较两个包含数字的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']
相关文章