V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
kknd22
V2EX  ›  Python

Python 排序如何做到与 Windows 一致?

  •  
  •   kknd22 · 2015-10-12 16:22:03 +08:00 · 2957 次点击
    这是一个创建于 3090 天前的主题,其中的信息可能已经有所发展或是发生改变。
    由于特殊需求,要让 Python 排序完全符合 windows 按名称排序的规则排序文件名,这样应该如何做到?
    比如几个文件名排序后, python 会把 "win_1.txt" 放到"_win1.txt"前边,而 windows 则会相反,特殊符号在前。
    9 条回复    2015-10-14 13:20:04 +08:00
    codeforlife
        1
    codeforlife  
       2015-10-12 16:35:56 +08:00
    列表排序么
    kknd22
        2
    kknd22  
    OP
       2015-10-12 16:47:46 +08:00
    @codeforlife 是的,列表排序
    codeforlife
        3
    codeforlife  
       2015-10-12 16:54:04 +08:00
    @kknd22
    你可以通过比较函数,先定义比较函数:

    def compare(x, y):
    x - y

    然后排序 :
    list.sort(cmp = compare)
    tobyxdd
        4
    tobyxdd  
       2015-10-12 17:11:33 +08:00 via Android
    windows 排序大体规则还是按字母的。。特殊的既然规则也已经知道了就自己微调?
    staticor
        5
    staticor  
       2015-10-12 17:18:09 +08:00
    map 字符串每个字符 -> ascii 值 (或自定义); 再据此排序
    Strikeactor
        6
    Strikeactor  
       2015-10-12 17:22:06 +08:00
    自己写呗。。你还希望 Pyhton 专门做个函数去兼容 Windows 的排序么
    tulongtou
        7
    tulongtou  
       2015-10-12 17:26:39 +08:00
    <img src="//cdn.v2ex.co/avatar/8091/58b6/131707_normal.png?m=1439002137" class="avatar" border="0" align="default">
    guoyijun163
        8
    guoyijun163  
       2015-10-13 11:59:58 +08:00   ❤️ 2
    Shlwapi = windll.LoadLibrary("Shlwapi")
    @WINFUNCTYPE(c_int, LPCWSTR, LPCWSTR)
    def compare_string(first_str, second_str):
    return Shlwapi.StrCmpLogicalW(first_str, second_str)

    调用一个 WIN32 API
    kknd22
        9
    kknd22  
    OP
       2015-10-14 13:20:04 +08:00
    @guoyijun163
    用这个方法搞定了
    另外谢谢所有朋友
    @codeforlife @tobyxdd @staticor @Strikeactor @tulongtou @guoyijun163
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3205 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:04 · PVG 08:04 · LAX 17:04 · JFK 20:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.