双循环解决添加列表问题

# 3.给定数组[0-9] 和 boll_array[0111011110], 0表示可以输出,
# 也可以不输出, 1必须输出对应位,输出所有可能情况(按字符串升序)
import copy
a = [0,1,2,3,4,5,6,7,8,9] # 数字数组
b = [0,1,1,1,0,1,1,1,1,0] # 对应的布尔值数组
# b = list(map(int,input().strip().split()))
index = []
for i in range(0,len(b)):
if b[i] == 1:
b[i] = str(i) # 将布尔值为1的位置赋予对应的数值
if b[i] == 0:
index.append(i) # 记录布尔值为0的位置索引
b[i] = '' # 同时赋予空
res = [b]
for ind in index:
for i in range(len(res)):
c= copy.copy(res[i])#这里的copy就是为了要一个一样的列表然后添加
c[ind] = str(ind) # 对结果列表中的每个组合依次添加布尔值为0的位置所对应的数字
res.append(c)
for i in range(len(res)):
res[i] = ''.join(res[i])
res.sort() # 排序
for i in res:
print(i)

[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', '']]
[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', ''], ['', '1', '2', '3', '4', '5', '6', '7', '8', '']]
[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', ''], ['', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '']]
[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', ''], ['', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['', '1', '2', '3', '', '5', '6', '7', '8', '9']]
[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', ''], ['', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['', '1', '2', '3', '', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '', '5', '6', '7', '8', '9']]
[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', ''], ['', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['', '1', '2', '3', '', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '', '5', '6', '7', '8', '9'], ['', '1', '2', '3', '4', '5', '6', '7', '8', '9']]
[['', '1', '2', '3', '', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '', '5', '6', '7', '8', ''], ['', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['0', '1', '2', '3', '4', '5', '6', '7', '8', ''], ['', '1', '2', '3', '', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '', '5', '6', '7', '8', '9'], ['', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']]
012345678
0123456789
01235678
012356789
12345678
123456789
1235678
12356789

通过输出能更好的看到列表添加的过程这个方法里面的循环相当于是2而外面的循环相当于是2的次方然后把一个列表再套一个列表方便添加lis=[[1,23,,4]]这种形式

猜你喜欢

转载自www.cnblogs.com/huhuxixi/p/10280186.html