在Python中生成布尔列表的组合/排列,不使用ITERTOOLS

5 投票
4 回答
4766 浏览
提问于 2025-04-18 01:49
l = [True, True , False]

不使用 itertools 模块。

你怎么能在一个新的 list 中创建列表 l 的所有排列呢?

newlist = [[True,True,False],[True,True,True], [False,False,True],[False,False,False]....]

基本上我想做的就是这个:

allorderings = itertools.product ([False, True], repeat = n)

4 个回答

0

试试这个,

>>> import itertools
>>> print list(itertools.permutations([True, True , False], 3))

输出结果

[(True, True, False), (True, False, True), (True, True, False), (True, False, True), (False, True, True), (False, True, True)]

或者试试这个,

>>> def combiList(l):
        if not l:
            return [[]]
        res = []
        for e in l:
            temp = l[:]
            temp.remove(e)
            res.extend([[e] + r for r in combiList(temp)])

        return res


>>> combiList([True, True , False])
[[True, True, False], [True, False, True], [True, True, False], [True, False, True], [False, True, True], [False, True, True]]
>>>
1

在官方文档中,有没有纯Python实现的和 itertools.permutations 相同功能的代码?

2

我想到的最简单的方法就是对同一份物品列表进行三次循环,然后只收集那些独一无二的物品,像这样:

l = set([True, True, False])
print {(i, j, k) for i in l for j in l for k in l}
4

使用 itertools.permutations

import itertools
l = [True, True , False]
newlist = list(itertools.permutations(l))

补充说明:从你的问题来看,你需要的其中一个排列是 (True, True, True),但这根本不是列表 l 的一个排列。这个回答给你的是列表的排列组合,从技术上讲是这样,但你可能还需要额外的工作才能实现你在问题中展示的内容(当然,如果那是个笔误就另当别论了)。

撰写回答