如何使用python生成规定长度01序列全排列的字符串

1、使用python生成全排列数据

在python中,实现了组合函数combinations和排列函数permutations。

1.1、permutations

import itertools as it
a=list(it.permutations(range(3),3))
print(a)
可以发现,range()中是生成列表的数值范围,后面一个数字是每个列表元素的长度

1.2、poduct

但是,当需要生成01序列的时候,就需要product函数了

import itertools as it
s = list(it.product(range(2), repeat=5))
print(s)

2、使用python对生成的序列完成字符串的转化

我现在想要[‘00’,‘01’,‘10’,‘11’]的格式该怎么办呢? 上面生成的结果每一个列表元素是元组,元组可以转化成字符串,但是,只限于元组的元素是字符,如果是数字的话,强制转换会出错的,因此,只能遍历转换。

这里复习一下字符串和元组列表的互转
  1. 元组、列表转字符串
#元组和列表转换的方法是一样的,都用到了join函数进行转换
a = (a,b,c,d,e)
b = "*".join(a)
print(a:,a)
print(b:,b)
  1. 字符串转列表、元组
#字符串转列表
a="abcd"
b=list(a)
  1. 数字和字符串的互转
#数字进行转换字符串常用的有两种
#1、数字转字符
a=3
b=%d%a
不要做强制转换,会出错
#字符串转换位数字
import string
a=555
b=string.atoi(a)
c=int(a)

3、最终代码

import itertools
m = list(itertools.product(range(2), repeat=2))
res=[]
for i in m:
    a=[]
    for j in i:
        a.append(%d%j)
    b=.join(a)
    res.append(b)
for i in res:
    print(i,end=" ")
    print(type(i))
经验分享 程序员 微信小程序 职场和发展