Python实现按中文排序的方法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现按中文排序的方法。分享给大家供大家参考,具体如下:

安装中文库

sudo apt-get update
sudo apt-get install language-pack-zh-hans-base
sudo dpkg-reconfigure locales

使用

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))

测试用例

输入

# -*- 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===
东挂南枝自

本机测试输出效果如下图:

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程序设计有所帮助。

相关文章

python通过post提交数据的方法

本文实例讲述了python通过post提交数据的方法。分享给大家供大家参考。具体实现方法如下: # -*- coding: cp936 -*- import urllib2 impo...

tensorflow实现加载mnist数据集

tensorflow实现加载mnist数据集

mnist作为最基础的图片数据集,在以后的cnn,rnn任务中都会用到 import numpy as np import tensorflow as tf import matpl...

Python中防止sql注入的方法详解

前言 大家应该都知道现在web漏洞之首莫过于sql了,不管使用哪种语言进行web后端开发,只要使用了关系型数据库,可能都会遇到sql注入攻击问题。那么在Python web开发的过程中s...

Django框架 查询Extra功能实现解析

extra extra(select=None, where=None, params=None, tables=None, order_by=None, select_pa...

安装Python的教程-Windows

安装Python的教程-Windows

在开始Python编程前,需要先安装Python环境。Python安装包可以到Python的官网下载,官网地址是https://www.python.org/,如果想直接跳过关于Pyth...