PHPのNATSORT関数のPythonアナログ(「自然な順序」アルゴリズムを使用してリストを並べ替える)[複製

StackOverflow https://stackoverflow.com/questions/2545532

  •  23-09-2019
  •  | 
  •  

質問

この質問にはすでに答えがあります:

似たようなものがあるかどうか知りたい php natsort Pythonの機能?

l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
l.sort()

与える:

['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']

しかし、私は取得したい:

['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

アップデート

ソリューションベース このリンク

def try_int(s):
    "Convert to integer if possible."
    try: return int(s)
    except: return s

def natsort_key(s):
    "Used internally to get a tuple by which s is sorted."
    import re
    return map(try_int, re.findall(r'(\d+|\D+)', s))

def natcmp(a, b):
    "Natural string comparison, case sensitive."
    return cmp(natsort_key(a), natsort_key(b))

def natcasecmp(a, b):
    "Natural string comparison, ignores case."
    return natcmp(a.lower(), b.lower())

l.sort(natcasecmp);
役に立ちましたか?

解決

から 私の答え自然ソートアルゴリズム:

import re
def natural_key(string_):
    """See http://www.codinghorror.com/blog/archives/001018.html"""
    return [int(s) if s.isdigit() else s for s in re.split(r'(\d+)', string_)]

例:

>>> L = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> sorted(L)
['image1.jpg', 'image12.jpg', 'image15.jpg', 'image3.jpg']
>>> sorted(L, key=natural_key)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

ユニコード文字列をサポートするには、 .isdecimal() ではなく使用する必要があります .isdigit(). 。の例を参照してください @Phihagのコメント. 。関連している: Unicodes数値プロパティを明らかにする方法.

.isdigit() 失敗する可能性もあります(認められない返品値 int())いくつかのロケールのPython 2でのバイテストリングなど、 Windows上のcp1252ロケールの ' xb2'( '²').

他のヒント

サードパーティを確認できます natsort Pypiのライブラリ:

>>> import natsort
>>> l = ['image1.jpg', 'image15.jpg', 'image12.jpg', 'image3.jpg']
>>> natsort.natsorted(l)
['image1.jpg', 'image3.jpg', 'image12.jpg', 'image15.jpg']

完全な開示、私は著者です。

この関数は、として使用できます key= の議論 sorted Python 2.xおよび3.xで:

def sortkey_natural(s):
    return tuple(int(part) if re.match(r'[0-9]+$', part) else part
                for part in re.split(r'([0-9]+)', s))
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top