使用python中的while循环更新位列表

时间:2018-08-03 04:41:51

标签: python list binary

我有一个清单。问题是我需要根据我拥有的新位来更新该位的值。这是我的代码示例:

count=1
cycle=3
bit_list = ['1','0','1','0']
new_bit=['1','0','1']
no=''.join(bit_list)
bit=''.join(new_bit)

while (count<=cycle):
    for b in no:
        print (b)
    print ("end of cycle", count)
    def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:]
    update=bin_add(no,bit)
    count=count+1
print ("updated list",update)

我需要以下输出:

1
0
1
0
updated list 1011  #1010 + 1
end of cycle 1
1
0
1
1
updated list 1011  #1011 + 0
end of cycle 2
1
0
1
1
updated list 1100   #1011 + 1
end of cycle 3

请帮助我解决此问题。谢谢。

1 个答案:

答案 0 :(得分:1)

您希望输出位于变量update中,但是循环仍然使用nobit进行操作,因此update不会在每次迭代后演化。您还应该仅将当前索引的位添加到输出中。您还应该在迭代结束时而不是在开始时输出“周期结束”消息:

count=1
cycle=3
bit_list = ['1','0','1','0']
new_bit=['1','0','1']
no=''.join(bit_list)
bit=''.join(new_bit)
while (count<=cycle):
    def bin_add(*args): return bin(sum(int(x, 2) for x in args))[2:]
    no=bin_add(no,bit[count - 1])
    for b in no:
        print (b)
    print ("end of cycle", count)
    count=count+1
print ("updated list",no)

这将输出:

1
0
1
1
end of cycle 1
1
0
1
1
end of cycle 2
1
1
0
0
end of cycle 3
updated list 1100