从二进制转换为十进制时,没有找回整个列表

时间:2018-08-26 14:29:08

标签: python

我正在尝试将列表中的整数转换为二进制,反之亦然。但由于某种原因,我只能返回最后一个整数,而不是整个列表。

redChannelData = [46, 49, 50, 51, 53, 53, 54, 56, 59, 59, 60, 61, 62, 62, 64, 64, 65, 65]

for value in redChannelData:
    encoded = [bin(value)[2:]]
    print(encoded)

for binary in encoded:
    decoded = [int(binary ,2)]
    print(decoded)
输出:
['101110']
['110001']
['110010']
['110011']
['110101']
['110101']
['110110']
['111000']
['111011']
['111011']
['111100']
['111101']
['111110']
['111110']
['1000000']
['1000000']
['1000001']
['1000001']
[65]

2 个答案:

答案 0 :(得分:1)

for value in redChannelData:
    encoded = [bin(value)[2:]]
    print(encoded)

在上面的循环中,您正在创建一个元素列表并进行打印。循环结束后,encoded的最后一个值是65。您可以将encoded创建为空列表,然后将二进制值附加到循环中。

答案 1 :(得分:0)

    with a list-comprehension     

        [bin(i)[2:] for i in redChannelData]  

        Out[32]:    

        ['101110',
         '110001',
         '110010',
         '110011',
         '110101',
         '110101',
         '110110',
         '111000',
         '111011',
         '111011',
         '111100',
         '111101',
         '111110',
         '111110',
         '1000000',
         '1000000',
         '1000001',
         '1000001']