python - 多个列表的可能组合
问题描述
我在列表中有一组变量
list = [ 'A', 'B', 'C']
我迭代地从列表中删除一个变量并将其附加到列表列表中的原始列表中,当列表只有一项时停止。例如,使用上面列表的输出将是:
list_of_var_lists = [
[['A', 'B', 'C'], ['A', 'B'], ['A']],
[['A', 'B', 'C'], ['A', 'B'], ['B']],
[['A', 'B', 'C'], ['A', 'C'], ['A']],
[['A', 'B', 'C'], ['A', 'C'], ['C']],
[['A', 'B', 'C'], ['B', 'C'], ['B']],
[['A', 'B', 'C'], ['B', 'C'], ['C']]
]
我将如何处理任何大小的列表?
非常感谢,J
解决方案
这是使用itertools.permutations的解决方案。它是一个生成器,而不是大量列表列表,因为此类子列表的数量呈超指数增长:
import itertools
def list_unpacker(ls):
for p in itertools.permutations(ls):
sublists = []
current_list = ls[:]
sublists.append(current_list)
for x in p[:-1]:
current_list = [y for y in current_list if y != x]
sublists.append(current_list)
yield sublists
for lists in list_unpacker(['a','b','c']):
print(lists)
输出:
[['a', 'b', 'c'], ['b', 'c'], ['c']]
[['a', 'b', 'c'], ['b', 'c'], ['b']]
[['a', 'b', 'c'], ['a', 'c'], ['c']]
[['a', 'b', 'c'], ['a', 'c'], ['a']]
[['a', 'b', 'c'], ['a', 'b'], ['b']]
[['a', 'b', 'c'], ['a', 'b'], ['a']]
推荐阅读
- node.js - 在提供的文件夹中递归读取图像文件
- javascript - 为什么我的浏览器没有打开 websocket 连接?
- php - 使用 PHP 中的 EXEC 函数在 Powershell 中使用 ConvertFrom-Json 获取传入的 PHP 参数(json_eoncoded 数组)时出错
- kubernetes - 是否可以在 Kubernetes 的不同命名空间中拥有超过 1 个角色和 1 个服务帐户?
- java - Java中单链表中addFirst方法的实现返回null?
- expression - 这种语言的表达
- python - 将 Tkinter 组合框绑定到条目更改?
- java - 如果多次选择无效的菜单项,我正在尝试弹出一条消息
- git - 如何在 git-rebase TODO 编辑器会话中查看更多日志行?
- javascript - 如何在 CDN 模式下测试 Vue?