Home > Software design >  How do I iterate through nested lists of binary digits and append their decimal number to a list? ex
How do I iterate through nested lists of binary digits and append their decimal number to a list? ex

Time:01-11

binary_list = [['0', '0', '1', '0', '1'], ['1', '0', '1', '0', '1'], ['0', '0', '0', '0', '0'], ['0', '1', '0', '0', '1'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '1'], ['0', '0', '0', '1', '0'], ['0', '0', '1', '0', '0']]

cipher_value = []

cipher_num = 0

for list in binary_list:
        for num in range(len(list)):
         
            if num == 0 and list[num] == 1:
                cipher_num  = 16
            elif num == 0 and list[num] == 0:
                continue
                
            if num == 1 and list[num] == 1:
                cipher_num  = 8
            elif num == 1 and list[num] == 0:
                continue
                
            if num == 2 and list[num] == 1:
                cipher_num  = 4
            elif num == 2 and list[num] == 0:
                continue
                
            if num == 3 and list[num] == 1:
                cipher_num  = 2
            elif num == 3 and list[num] == 0:
                continue
            
            if num == 4 and list[num] == 1:
                cipher_num  = 1
            elif num == 4 and list[num] == 0:
                continue
                
            cipher_value.append(cipher_num)
            cipher_num = 0
            break

CodePudding user response:

You can use int(..., 2) to convert the binary representation (in string type) of a number into an integer. So, with help of join and list comprehension:

cipher_value = [int(''.join(sublist), 2) for sublist in binary_list]
print(cipher_value) # [5, 21, 0, 9, 24, 5, 2, 4]

CodePudding user response:

For each element in the list, you can convert the binary representation to a decimal integer by using bit-shifting. This has the advantage of being able to work with a variable number of binary numbers, as well as variable-length binary numbers:

binary_list = [['0', '0', '1', '0', '1'], ['1', '0', '1', '0', '1'], ['0', '0', '0', '0', '0'], ['0', '1', '0', '0', '1'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '1'], ['0', '0', '0', '1', '0'], ['0', '0', '1', '0', '0']]

cipher_values = []
for binary_repr in binary_list:
    cipher_num = 0
    for bit in binary_repr:
        cipher_num <<= 1
        cipher_num  = int(bit)
    cipher_values.append(cipher_num)
print(cipher_values)
  •  Tags:  
  • Related