本文實(shí)例講述了Python實(shí)現(xiàn)按中文排序的方法。分享給大家供大家參考,具體如下:
安裝中文庫
1
2
3
|
sudo apt - get update sudo apt - get install language - pack - zh - hans - base sudo dpkg - reconfigure locales |
使用
1
2
3
4
|
import locale locale.setlocale(locale.LC_COLLATE, 'zh_CN.UTF8' ) cmp = locale.strcoll courses.sort( lambda x, y: cmp (x.course_name, y.course_name)) |
測試用例
輸入
1
2
3
4
5
6
7
8
9
10
|
# -*- coding: utf-8 -*- import locale #locale.setlocale(locale.LC_COLLATE, 'zh_CN.UTF8') cmp = locale.strcoll items = 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===
東掛南枝自
本機(jī)測試輸出效果如下圖:
希望本文所述對(duì)大家Python程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/xiaobuding007/article/details/78224159