如何在python中缩短二进制到十进制转换器的列表

时间:2014-07-08 11:17:14

标签: python

我有一个很长的列表来解决二进制问题(作为输入),我不知道如何缩短它

所以这是代码

conversion = input("Enter an 8 bit  binary number to convert: ")

conversion = list(conversion)

ok = False;

if conversion[0] == '0':
    ok = True

if conversion[0] == '1':
    ok = True

if conversion[1] == '0':
    ok = True

if conversion[1] == '1':
    ok = True

if conversion[2] == '0':
    ok = True

if conversion[2] == '1':
    ok = True

if conversion[3] == '0':
    ok = True

if conversion[3] == '1':
    ok = True

if conversion[4] == '0':
    ok = True

if conversion[4] == '1':
    ok = True

if conversion[5] == '0':
    ok = True

if conversion[5] == '1':
    ok = True

if conversion[6] == '0':
    ok = True

if conversion[6] == '1':
    ok = True

if conversion[7] == '0':
    ok = True

if conversion[7] == '1':
    ok = True

if ok == True:
    print("Number is binary!")


n1 = 0

if conversion[7] == '1':
    n1 = 1

if conversion[6] == '1':
    n1 = n1 + 2

if conversion[5] == '1':
    n1 = n1 + 4

if conversion[4] == '1':
    n1 = n1 + 8

if conversion[3] == '1':
    n1 = n1 + 16

if conversion[2] == '1':
    n1 = n1 + 32

if conversion[1] == '1':
    n1 = n1 + 64

if conversion[0] == '1':
    n1 = n1 + 128

1 个答案:

答案 0 :(得分:0)

my_list = ["0","1","1","0","0","1","0","1"]

print all(x in ["0","1"] for x in my_list)