gpt4 book ai didi

python - 创建表示二进制值的字符串列表,具有固定长度

转载 作者:太空宇宙 更新时间:2023-11-04 08:37:13 42 4
gpt4 key购买 nike

我需要一个表示二进制值的字符串列表,具有固定长度,因此前导零。例如:

my_list = ["00", "01", "10", "11"]

我希望能够生成给定位数的列表。我想出了一个代码,但我不确定这是否是最好的方法,并且想知道是否可以用单行代码做同样的事情?

bits = 2
my_list = []
for i in range(2**bits):
my_list.append(format(i, '0b').zfill(bits))

最佳答案

您可以使用 itertools.product完成这个

from itertools import product 

def bitstrings(n):
return [''.join(bits) for bits in product('01', repeat=n)]

关于python - 创建表示二进制值的字符串列表,具有固定长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48085285/

42 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com