如果元素是邻居,是否有可能得到所有元素的组合?
这是示例:
编辑:我想在字符串上使用它,而不仅仅是数字。例如:[Explain,it,to,me,please]
列表:
[0,1,2,3,4]
结果:
[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]
结果中不会有 [0,2,3]
等,因为 0
和 2
不是邻居在上面的排序列表中。
我尝试使用 itertools.combinations
但它提供了所有组合。
最佳答案
你可以这样做:
>>> 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']]
关于python - 获取列表中相邻元素的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24515991/