加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 从String中的某个位置排序

发布时间:2020-12-20 11:37:53 所属栏目:Python 来源:网络整理
导读:收集这些类型的字符串: "foo: a message""bar: d message""bar: b message""foo: c message" 两个字符串foo:和bar:长度相同所以我想从位置5的索引开始排序所以我的输出将是…… "foo: a message""bar: b message""foo: c message""bar: d message" 解决方
收集这些类型的字符串:

"foo: a message"
"bar: d message"
"bar: b message"
"foo: c message"

两个字符串foo:和bar:长度相同所以我想从位置5的索引开始排序所以我的输出将是……

"foo: a message"
"bar: b message"
"foo: c message"
"bar: d message"

解决方法

使用键功能切割每个字符串;然后使用密钥产生的值进行排序.

sorted(inputlist,key=lambda s: s[5:])

演示:

>>> inputlist = ['foo: a message','bar: d message','bar: b message','foo: c message']
>>> sorted(inputlist,key=lambda s: s[5:])
['foo: a message','foo: c message','bar: d message']

引用sorted() documentation:

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读