本文介绍了将二进制转换为数字列表Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下情况:

x = 0b0111

我想将此值转换为:

y = [0, 1, 1, 1]

当我转换x = 0b1001时,我可以得到y = [1, 0, 0, 1],但是当我尝试对x = 0b0111做同样的操作,然后再用str(bin(y))转换回时-我似乎失去了前导的0,并且得到0b111.

When I convert x = 0b1001, I can get y = [1, 0, 0, 1], but when I try to do the same for x = 0b0111, and then convert back with str(bin(y)) - I seem to lose the leading 0, and get 0b111.

有什么建议吗?

推荐答案

一旦您获得了字符串0b111,就可以很容易地拆分出您感兴趣的数字.对于0b之后的所有字符,在字符串中,将其转换为整数.

Once you get that string 0b111, it's straightforward to split out the digits that you're interested in. For each character of everything after the 0b in the string, convert it to an integer.

[int(d) for d in str(bin(x))[2:]]

这篇关于将二进制转换为数字列表Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:43