本文实例讲述了Python实现按中文排序的方法。分享给大家供大家参考,具体如下:
安装中文库
sudo apt-get updatesudo apt-get install language-pack-zh-hans-basesudo dpkg-reconfigure locales使用
import localelocale.setlocale(locale.LC_COLLATE, 'zh_CN.UTF8')cmp = locale.strcollcourses.sort(lambda x, y: cmp(x.course_name, y.course_name))测试用例
输入
# -*- coding: utf-8 -*-import locale#locale.setlocale(locale.LC_COLLATE, 'zh_CN.UTF8')cmp = locale.strcollitems = list('自挂东南枝'.decode('utf-8'))print 'before'.center(10, '=')print ''.join(items)items.sort(lambda x, y: cmp(x, y))print 'after'.center(10, '=')print ''.join(items)输出
==before==
自挂东南枝
==after===
东挂南枝自
本机测试输出效果如下图:
PS:这里再为大家推荐2款比较实用的相关在线排序工具供大家参考使用:
在线中英文根据首字母排序工具:
http://tools.jb51.net/aideddesign/zh_paixu
在线文本倒序翻转排序工具:
http://tools.jb51.net/aideddesign/flipped_txt
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python列表(list)操作技巧总结》、《Python数组操作技巧总结》、《Python字符串操作技巧汇总》、《Python函数使用技巧总结》、《Python入门与进阶经典教程》及《Python数据结构与算法教程》
希望本文所述对大家Python程序设计有所帮助。