获取列表中的所有邻居元素组合

Mil*_*ano 5 python math combinations list

是否可以获得元素的所有组合,以防它们是邻居?
这是一个例子:

编辑:我想在字符串上使用它,而不仅仅是数字.例如:[Explain,it,to,me,please]

列表:

[0,1,2,3,4]
Run Code Online (Sandbox Code Playgroud)

结果:

[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]
Run Code Online (Sandbox Code Playgroud)

就不会有例如[0,2,3]等的结果,因为02没有在上面的排序列表的邻居.

我尝试使用,itertools.combinations但它提供了所有组合.

use*_*450 9

你可以做:

>>> 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]]
Run Code Online (Sandbox Code Playgroud)

然后,按降序长度和升序值排序:

>>> 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]]
Run Code Online (Sandbox Code Playgroud)

对于字符串,它会产生:

>>> 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']]
Run Code Online (Sandbox Code Playgroud)