How do I iterate through nested lists of binary digits and append their decimal number to a list? ex: [[0,0,1,0,1],[1,0,0,0,1]]==[5, 17]
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
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]