你可以这样做:
>>> L = [0,1,2,3,4]
>>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
>>> pprint.pprint(result)
[[0],
[0, 1],
[0, 1, 2],
[0, 1, 2, 3],
[0, 1, 2, 3, 4],
[1],
[1, 2],
[1, 2, 3],
[1, 2, 3, 4],
[2],
[2, 3],
[2, 3, 4],
[3],
[3, 4],
[4]]
然后,按长度降序和升序排序:
>>> result.sort(key=lambda x: (-len(x), x))
>>> pprint.pprint(result)
[[0, 1, 2, 3, 4],
[0, 1, 2, 3],
[1, 2, 3, 4],
[0, 1, 2],
[1, 2, 3],
[2, 3, 4],
[0, 1],
[1, 2],
[2, 3],
[3, 4],
[0],
[1],
[2],
[3],
[4]]
对于字符串,它会产生:
>>> L = ['Explain', 'it', 'to', 'me', 'please']
>>> result = [L[i:j] for i in xrange(len(L)) for j in xrange(i + 1, len(L) + 1)]
>>> result.sort(key=lambda x: (-len(x), x))
>>> pprint.pprint(result)
[['Explain', 'it', 'to', 'me', 'please'],
['Explain', 'it', 'to', 'me'],
['it', 'to', 'me', 'please'],
['Explain', 'it', 'to'],
['it', 'to', 'me'],
['to', 'me', 'please'],
['Explain', 'it'],
['it', 'to'],
['me', 'please'],
['to', 'me'],
['Explain'],
['it'],
['me'],
['please'],
['to']]