📜  Python|十进制到二进制列表的转换

📅  最后修改于: 2022-05-13 01:55:22.388000             🧑  作者: Mango

Python|十进制到二进制列表的转换

二进制列表到十进制数的转换已在上一篇文章中讨论过。本文旨在提供一些相反的速记,即二进制到十进制的转换。让我们讨论一些可以做到这一点的方法。

方法 #1:使用列表理解 + format()
在此方法中,十进制到二进制的转换由 format函数处理。转换为列表的逻辑由列表推导函数完成。

# Python3 code to demonstrate 
# decimal to binary number conversion
# using format() + list comprehension
  
# initializing number 
test_num = 38
  
# printing original number
print ("The original number is : " + str(test_num))
  
# using format() + list comprehension
# decimal to binary number conversion 
res = [int(i) for i in list('{0:0b}'.format(test_num))]
  
# printing result 
print ("The converted binary list is : " +  str(res))
输出:
The original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]


方法 #2:使用bin() + 列表推导
内置函数bin 执行转换为二进制的函数,列表推导处理将二进制数转换为列表的逻辑。

# Python3 code to demonstrate 
# decimal to binary number conversion
# using bin() + list comprehension
  
# initializing number 
test_num = 38
  
# printing original number
print ("The original number is : " + str(test_num))
  
# using bin() + list comprehension
# decimal to binary number conversion 
res = [int(i) for i in bin(test_num)[2:]]
  
# printing result 
print ("The converted binary list is : " +  str(res))
输出:
The original number is : 38
The converted binary list is : [1, 0, 0, 1, 1, 0]