首页 > 解决方案 > 在python中使用while循环更新位列表

问题描述

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

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

请帮我解决这个问题。谢谢你。

标签: pythonlistbinary

解决方案


您希望输出位于变量中update,但您的循环继续使用noand bitfor 操作,因此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

推荐阅读