简体   繁体   中英

How to convert binary, octal and quaternary lists into decimal lists?

I need to convert three lists into decimal lists to check maximum and minimum value in them. How can I do it? example Lists:

binary_list = [0, 0, 0, 0, 0, 1, 1, 10, 10, 11, 100, 100, 11, 10, 0]

quaternary_list = [-11, -33, -22, -132, -220, -310]

octal_list = [62, -220, -36, 5, 0, 1, -12]

If I understand your question correctly, you could do something like this ( try it online ):

binary_list = [0, 0, 0, 0, 0, 1, 1, 10, 10, 11, 100, 100, 11, 10, 0]
quaternary_list = [-11, -33, -22, -132, -220, -310]
octal_list = [62, -220, -36, 5, 0, 1, -12]

def list_to_decimal(lst, base):
    return [int(str(item), base) for item in lst]

print(list_to_decimal(binary_list, 2)) # => [0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 4, 3, 2, 0]
print(list_to_decimal(quaternary_list, 4)) # => [-5, -15, -10, -30, -40, -52]
print(list_to_decimal(octal_list, 8)) # => [50, -144, -30, 5, 0, 1, -10]

It works using a function list_to_decimal that takes a list lst and a base base , which then uses a list comprehension to interpret every element of lst as a number of base .

Does that answer your question?

You can do it like this.

binary_list = [0, 0, 0, 0, 0, 1, 1, 10, 10, 11, 100, 100, 11, 10, 0]
quaternary_list = [-11, -33, -22, -132, -220, -310]
octal_list = [62, -220, -36, 5, 0, 1, -12]

binary_list_do_dec = [int(str(i), 2) for i in binary_list]
quaternary_list_do_dec = [int(str(i), 4) for i in quaternary_list]
octal_list_do_dec = [int(str(i), 8) for i in octal_list]

print(binary_list_do_dec)
print(quaternary_list_do_dec)
print(octal_list_do_dec)

The output looks like:

[0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 4, 3, 2, 0]
[-5, -15, -10, -30, -40, -52]
[50, -144, -30, 5, 0, 1, -10]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM