简体   繁体   English

Python排序:子字符串

[英]Python sorting : sub strings

In Python 在Python中

s= "ABCC"
n = len(s)
sorted(set([s[a:b] for a in range(n) for b in range(a+1,n+2)])

gives me, alphabetically sorted sub strings with out repetitions 给我,按字母顺序排序的子字符串,没有重复

['A', 'AB', 'ABC', 'ABCC', 'B', 'BC', 'BCC', 'C', 'CC']

How can I further sort it by length of sub string. 如何进一步根据子字符串的长度对其进行排序。

['A', 'B', 'C', 'AB', 'BC', 'CC', 'ABC', 'BCC', 'ABCC']

simple, 简单,

sorted(set(s[a:b] for a in range(n) for b in range(a+1,n+1)),
       key=lambda x:(len(x),x))

This creates a key by which the comparison is done. 这将创建一个用于进行比较的密钥。 First it compares the string lengths to determine the order. 首先,它比较字符串长度以确定顺序。 If the strings have the same length, the tie-breaker is the string contents. 如果字符串长度相同,则决胜局为字符串内容。

This is your solution: 这是您的解决方案:

s= "ABCC"
n = len(s)
sorted(sorted(set([s[a:b] for a in range(n) for b in range(a+1,n+2)])),key=len)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM