Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading