python - 单个列表中可能的列表组合

标签 python list

给定列表

[[1,2],[3,4],[5,6]]

我希望输出为 3 个不同的列表,如下所示

[1,2,3,4],[3,4,5,6],[1,2,5,6]

最佳答案

您可以使用itertools.combinations获得所有可能的对

a = [[1, 2], [3, 4], [5, 6]]

>>> list(itertools.combinations(a, 2))
[([1, 2], [3, 4]), ([1, 2], [5, 6]), ([3, 4], [5, 6])]

要展平各个元素,只需映射它们并添加两个列表

>>> list(map(lambda x: x[0] + x[1], itertools.combinations(a, 2)))
[[1, 2, 3, 4], [1, 2, 5, 6], [3, 4, 5, 6]]

关于python - 单个列表中可能的列表组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59701091/

相关文章:

jQuery - append 列表,其中包含与 PHP 值一样多的选项

Python 3.3 将列表中的字符串写入 txt 文件

java - 如何检查 List<obj> 是否为空?

python - 在导入时装饰模块而不影响其他功能实现的功能

python - 从 __getattr__ 方法检索的模拟函数

python - 使用Python解析从USB读取的串行数据

python - ctypes bigendianstruct Littlendianstruct 对单字节返回不同的结果

python - 在没有mixin的情况下迭代类对象的字典 - python

c# - 如何从Unity3d和C#中的另一个脚本访问在单例类中创建的列表

python - 在Python中递归生成n个选择k个组合的列表 - 但返回一个列表