我有4个二进制数据字符串;我想使用每个列将输出作为整数,即
p1 = '10010010101111'
p2 = '11100011110001'
p3 = '00001110101101'
p4 = '00101100010010'
我想将输出作为整数作为 [p1 p2 p3 p4]
以下代码不断返回语法错误。我要去哪里错了?
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)
答案 0 :(得分:1)
您可以使用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]
答案 1 :(得分:0)
我在以下方面度过了轻松的时光:
p1 = '10010010101111'
p2 = '11100011110001'
p3 = '00001110101101'
p4 = '00101100010010'
p =[p1,p2,p3,p4]
y=[]
for element in p:
y.append(bin(int(element,2)))
print(y)
如果只想将二进制的十进制值作为整数,则不要将bin()放在上面的for循环中。
答案 2 :(得分:0)
另一种选择:
p1 = '10010010101111'
p2 = '11100011110001'
p3 = '00001110101101'
p4 = '00101100010010'
p = [p1,p2,p3,p4]
y = [int(x,2) for x in p]
答案 3 :(得分:0)
尝试一下:
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]