python - 在 Python 中生成一个 n 长度的位列表

标签 python permutation bit

我想要一个函数,它会给出指定长度的所有可能的字符串,这些字符串仅由零和一组成。例如:

spam(4)

应该得到我:

['0110', '0111', '0001', '0011', '0010', '0101', '0100', '1110', '1100', '1101', '1010', '1011', '1001', '1000']

我尝试使用 itertools.permutations 来完成这项工作。所以,这就是我所做的。

def getPerms(n):
    perms = getCandidates(n)
    res = []
    for i in perms:
        res.extend(permutations(i))
    res = clean(res)
    return res

def clean(ar):
    res = []
    for i in ar:
        temp = ""
        for j in i:
            temp += j
        res.append(temp)
    return list(set(res))

def getCandidates(n):
    res = []
    for i in range(1, n):
        res.append("1"*i + "0"*(n-i))
    return res

但这是非常低效的,并且在输入 10 时会出现内存错误。

最佳答案

使用itertools.product相反。

>>> import itertools
>>> [''.join(i) for i in itertools.product('01', repeat=4)]
['0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

使用函数(假设 itertools 已经导入):

def bitGen(n):
    return [''.join(i) for i in itertools.product('01', repeat=n)]

对于较大的 n,返回一个生成器可能更合适。

def bitGen(n):
    return (''.join(i) for i in itertools.product('01', repeat=n))

# Alternatively:

def bitGen(n):
    for i in itertools.product('01', repeat=n):
        yield ''.join(i)

关于python - 在 Python 中生成一个 n 长度的位列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15582905/

相关文章:

algorithm - 不重复排列

c - 旋转右位

python - 如果函数中断,如何从函数内部返回正确的数据?

python - 如何将两个图像与枕头组合(逻辑或)?

python - IN子句中使用的mysql命名占位符在python中

具有重复字符的 Python 长排列

python - 谷歌应用引擎本地开发服务器上的 OpenID 登录

具有重复的排列

c++ - 检查 WM_KEYDOWN 上的 LPARAM - 值不正确?

java - 正确使用位掩码?