python如何定义字符串,根据Python中的自定义字母对字符串值进行排序

I am looking for an efficient way to sort a list of strings according a custom alphabet.

For example, I have a string alphabet which is "bafmxpzv" and a list of strings composed from only the characters contained in that alphabet.

I would like a way to sort that list similarly to other common sorts, but using this custom alphabet. How can I do that?

解决方案

Let's create an alphabet and a list of words:

In [32]: alphabet = "bafmxpzv"

In [33]: a = ['af', 'ax', 'am', 'ab', 'zvpmf']

Now let's sort them according to where the letters appear in alphabet:

In [34]: sorted(a, key=lambda word: [alphabet.index(c) for c in word])

Out[34]: ['ab', 'af', 'am', 'ax', 'zvpmf']

The above sorts in the correct order.

sorted enables a wide range of custom sorting. The sorted function has three optional arguments: cmp, key, and reverse:

cmp is good for complex sorting tasks. If specified, cmp should be a functionIt that takes two arguments. It should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. For this case, cmp is overkill.

key, if spedified, should be a function that takes one argument and returns something that python knows natively how to sort. In this case, key returns a list of the indices of each of the word's characters in the alphabet.

In this case, key returns the index of a letter in alphabet.

reverse, if true, reverses the sort-order.

A nonworking alternative

From the comments, this alternative form was mentioned:

In [35]: sorted(a, key=lambda word: [alphabet.index(c) for c in word[0]])

Out[35]: ['af', 'ax', 'am', 'ab', 'zvpmf']

Note that this does not sort in the correct order. That is because the key function here only considers the first letter of each word. This can be demonstrated by testing key:

In [2]: key=lambda word: [alphabet.index(c) for c in word[0]]

In [3]: key('af')

Out[3]: [1]

In [4]: key('ax')

Out[4]: [1]

Observe that key returns the same value for two different strings, af and ax. The value returned reflects only the first character of each word. Because of this, sorted has no way of determining that af belongs before ax.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值