比较两个包含数字的 python 字符串 [英] compare two python strings that contain numbers

查看:61
本文介绍了比较两个包含数字的 python 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:我应该早点指定这一点,但并非所有名称都只是浮点数.例如,其中一些前缀"为YT".所以例如YT1.1.所以,你有同样的问题 YT1.9 < YT1.11 应该是真的.我真的很惊讶字符串比较失败......

你好,这应该是一个非常简单的问题,但我似乎找不到答案.我想按名称对一堆 XL 工作表进行排序.每个名称都是数字,但与教科书部分"的编号方式相同,这意味着第 4.11 节在 4.10 之后,这两者都在 4.9 和 4.1 之后.我认为简单地将这些数字作为字符串进行比较就可以了,但我得到以下结果:

<预><代码>>>>s1 = '4.11'>>>s2 = '4.2'>>>s1>s2错误的>>>n1 = 4.11>>>n2 = 4.2>>>n1>n2错误的

如何比较这两个值,使 4.11 大于 4.2?

解决方案

将名称转换为整数元组并比较元组:

def splittedname(s):return tuple(int(x) for x in s.split('.'))拆分名称(s1)>拆分名称(s2)

更新:由于您的姓名显然可以包含数字以外的其他字符,您需要检查 ValueError 并留下任何无法转换为整数的值不变:

导入重新def tryint(x):尝试:返回整数(x)除了值错误:返回 xdef splittedname(s):return tuple(tryint(x) for x in re.split('([0-9]+)', s))

要对名称列表进行排序,请使用 splittedname 作为 sorted 的关键函数:

<预><代码>>>>名称 = ['YT4.11'、'4.3'、'YT4.2'、'4.10'、'PT2.19'、'PT2.9']>>>排序(名称,键=拆分名称)['4.3'、'4.10'、'PT2.9'、'PT2.19'、'YT4.2'、'YT4.11']

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

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

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)

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

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 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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