python字符串排序,在Python中对字符串列表进行排序

I have a list of strings list and want to sort it alphabetically. When I call list.sort() the first part of the list contains the entries starting with upper case letters sorted alphabetically, the second part contains the sorted entries starting with a lower case letter. Like so:

Airplane

Boat

Car

Dog

apple

bicycle

cow

doctor

I googled for an answer but didn't came to a working algorithm. I read about the locale module and the sort parameters cmp and key. Often there was this lambda in a row with sort, which made things not better understandable for me.

How can I get from:

list = ['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat', 'apple', 'Airplane']

to:

Airplane

apple

bicycle

Boat

Car

cow

doctor

Dog

Characters of foreign languages should be taken into account (like ä, é, î).

解决方案

Use case-insensitive comparison:

>>> sorted(['Dog', 'bicycle', 'cow', 'doctor', 'Car', 'Boat',

'apple', 'Airplane'], key=str.lower)

['Airplane', 'apple', 'bicycle', 'Boat', 'Car', 'cow', 'doctor', 'Dog']

This is actually the way suggested on the python wiki about sorting:

Starting with Python 2.4, both list.sort() and sorted() added a key

parameter to specify a function to be called on each list element

prior to making comparisons.

For example, here's a case-insensitive string comparison:

>>> sorted("This is a test string from Andrew".split(), key=str.lower)

['a', 'Andrew', 'from', 'is', 'string', 'test', 'This']

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值