代码之家  ›  专栏  ›  技术社区  ›  user479870

对Python中的名称列表排序,忽略数字?

  •  4
  • user479870  · 技术社区  · 15 年前
    ['7', 'Google', '100T', 'Chrome', '10', 'Python']
    


    Chrome
    Google
    Python
    100T
    7
    10
    

    不过,这稍微复杂一点,因为我是按价值对字典排序的。

    def sortname(k): return get[k]['NAME']
    sortedbyname = sorted(get,key=sortname)
    

    我只是在两个答案都发布后才添加了100T,但接受的答案仍然有效,我在评论中发布了一个小修改。为了澄清,应该对与^[^0-9]匹配的名称进行排序。

    2 回复  |  直到 15 年前
        1
  •  3
  •   Marcelo Cantos    15 年前

    我一直在努力让字典版本工作,下面是数组版本供您推断:

    def sortkey(x):
        try:
            return (1, int(x))
        except:
            return (0, x)
    
    sorted(get, key=sortkey)
    

        2
  •  1
  •   adw    15 年前
    >>> l = ['7', 'Google', 'Chrome', '10', 'Python']
    >>> sorted(l, key=lambda s: (s.isdigit(), s))
    ['Chrome', 'Google', 'Python', '10', '7']
    

    Python的排序是稳定的,因此也可以使用多个连续的排序:

    >>> m = sorted(l)
    >>> m.sort(key=str.isdigit)
    >>> m
    ['Chrome', 'Google', 'Python', '10', '7']