使用索引将二进制字符串转换为整数数组

2024-03-28 11:00:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有4个二进制数据字符串;我想使用每个字符串的列将输出作为整数,即

p1 = '10010010101111' 
p2 = '11100011110001' 
p3 = '00001110101101' 
p4 = '00101100010010'

我想把输出作为整数作为[p1p2p3p4]

下面的代码不断返回语法错误。我哪里出错了?你知道吗

for i in range(0,len(p1),1):
    x = [p1[i],p2[i],p3[i],p4[i]]
    y = ''.join(map(str,x))
    z[i] = int(y,2)

Tags: 数据字符串代码inforlen二进制range
3条回答

试试这个:

p1 = '10010010101111' 
p2 = '11100011110001' 
p3 = '00001110101101' 
p4 = '00101100010010'
p =[p1,p2,p3,p4]
z = list(map(int, p)) # Keeps the strings in binary format
z1 = [int(i,2) for i in p] # Converts strings to decimal formatted integer

输出

[10010010101111, 11100011110001, 1110101101, 101100010010]
[9391, 14577, 941, 2834]

可以使用zip()转置列和本机二进制字符串转换以获得数值:

z = [ int("".join(bits),2) for bits in zip(p1,p2,p3,p4) ]
print(z) # [12, 4, 5, 8, 3, 3, 14, 4, 14, 5, 10, 10, 9, 14]

另一种选择:

p1 = '10010010101111' 
p2 = '11100011110001' 
p3 = '00001110101101' 
p4 = '00101100010010'

p = [p1,p2,p3,p4]

y = [int(x,2) for x in p]

相关问题 更多 >