本文實例講述了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===
東掛南枝自
本機測試輸出效果如下圖:

希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答