python - 获取列表中相邻元素的所有组合

标签 python list math combinations

如果元素是邻居,是否有可能得到所有元素的组合?
这是示例:

编辑:我想在字符串上使用它,而不仅仅是数字。例如:[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] 等,因为 02 不是邻居在上面的排序列表中。

我尝试使用 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/

相关文章:

string - 从 List<String> 转换为 List<Character> Java

c# - Entity Framework 核心 ForEachAsync

python - 在 Python 中创建包含列表列表的字典

python - 如何测试一个列表是否包含另一个包含 Python 中特定项目的列表?

python - cx_Oracle.DatabaseError : DPI-1047: 64-bit Oracle Client library cannot be loaded: "dlopen(libclntsh.dylib, 1): image not found"

python - Django 中菜单和子菜单的递归函数,直到最后一个子菜单出现

c# - 如何通过具有容差因子的数值对对象进行 GroupBy?

javascript - 二次计算器给出 Nan

java - 使用埃拉托色尼筛法寻找第 n 个素数

Python:在元组列表中查找最接近的匹配项