2014-02-25 47 views
-2

我有兴趣在python中比较单数字字符和多数字字符。该比较应该产生,在python中比较字符串

'A' < 'AB' TRUE 
'B' < 'AB' TRUE 
'Z' < 'AB' TRUE 
'AA' < 'AB' TRUE 
'AC' < 'AB' FALSE 

任何关于如何做到这一点的线索。该字符串是从最小的命令最大如下,

['A','B',....'Z','AA','AB',....'AZ','BA',....'BZ'.......] 
+0

你能描述比较的逻辑吗? – mhlester

+0

不应该将'AC'<'AB''设为真,并且'AA'<'AB''为假? – TerryA

+0

我已经添加了一些原来的问题,以解释他们如何订购 – nitin

回答

4

你想通过长先比较,然后按字典。

def comparison(x): 
    return len(x), x 

comparison返回两项目元组。首先len(x),然后x。这些排序的顺序

使用您的输入:

>>> comparison('A') < comparison('AB') 
True 
>>> comparison('B') < comparison('AB') 
True 
>>> comparison('Z') < comparison('AB') 
True 
>>> comparison('AA') < comparison('AB') 
True 
>>> comparison('AC') < comparison('AB') 
False 
3

的长度进行比较,然后通过字典顺序:

def compare_key(string): 
    return len(string), string 

if compare_key(s1) < compare_key(s2): 
    do_something() 
elif compare_key(s1) > compare_key(s2): 
    do_other_thing() 
else: 
    do_third_thing() 
1

其他的答案是冷的。这只返回1,-1和0.

def compare(a,b): 
    d = len(a) - len(b) 
    if d==0: 
     if a < b: return -1 
     if a > b: return 1 
     return 0 
    return 1 if d>0 else -1