在Python中将包含十进制数字的列表转换为二进制

时间:2018-10-29 21:12:44

标签: python python-3.x list binary

我有一个作为整数的十进制数字列表,我想将它们转换为二进制。输出必须不带 Pie charts are a very bad way of displaying information. The eye is good at judging linear measures and bad at judging relative areas. A bar chart or dot chart is a preferable way of displaying this type of data. Cleveland (1985), page 264: "Data that can be shown by pie charts always can be shown by a dot chart. This means that judgements of position along a common scale can be made instead of the less accurate angle judgements." This statement is based on the empirical investigations of Cleveland and McGill as well as investigations by perceptual psychologists. 前缀,并且必须为4位数字 喜欢:

0b

提前感谢

4 个答案:

答案 0 :(得分:2)

您可以在此处将mapformat一起使用'04b'

>>> list(map(lambda x: format(x,'04b'),lista))
['0001', '0010', '0011', '0100', '0101', '0110', '0111', '1000', '1001', '1010']

答案 1 :(得分:2)

另一种实现此目的的方法是:

listres = [str(bin(x))[2:].zfill(4) for x in lista]

答案 2 :(得分:0)

这听起来像是功课,所以我只对如何创建第二个列表提供建议。如果您知道如何将整数转换为二进制表示形式,则可以使用列表推导:

lista = [1,2,3,4,5,6,7,8,9,10]
listb = [integer_to_binary(n) for n in lista]

在这里,integer_to_binary()只是将整数转换为二进制表示形式的函数。听起来您想要的是一个显示二进制表示形式的字符串,所以我让您自己找出(提示:尝试使用format())

答案 3 :(得分:-1)

使用bin方法;

>>> a = bin(6)
>>>a

'0b110'
a[2:]
110