2017-06-22 28 views
1

我正在使用python-3.x,我試圖將[x]數組中的每個二進制行分成兩部分,前四位數字將使第一個數字和第二個四位數字作爲secund數字後我將它們轉換爲浮動。劃分二進制行並將每個部分轉換爲浮點數或十進制數python 3

有一個函數「def test(binary)」,它將執行從二進制到浮點數的轉換,並且有兩個循環遍歷數組。

例如,第一行是:[1,0,0,1,0,0,0,0] 我想把它分成1001 - 1000 那麼最終的結果是[9,8 ]

import numpy as np 
n = 4 

################################## 
# convert a list of Binary's to decimal 
def test(binary): 
    wordlength = binary.shape[1] 
    shift = np.arange(wordlength-1, -1, -1) 
    decimal = np.sum(binary << shift, 1) 
    print (decimal) 
################################## 

np.set_printoptions(threshold=np.nan) 


x = np.array([[1, 0, 0, 1, 1, 0, 0, 0], 
      [1, 1, 1, 1, 1, 0, 0, 0], 
      [1, 0, 0, 1, 1, 1, 0, 1]]) 

print(x) 

for ii in range (3) : 
    start_array = 0 
    X = x[ii] 
    print ("X:" '\n', X) 
    #print(ii, X) 

    for i in range (2) : 
     end_array= start_array + n 
     print ("end_array:" '\n', end_array) 
     print ("start_array:" '\n', start_array) 
     flot = np.zeros ((3, 2)) 
     flot[ii, i] = test(x[start_array:end_array]) 

     print (flot) 
     start_array=end_array 

,但我不能得到正確的結果,我不知道哪裏出了問題,如果我的方式來解決這個問題是對的

回答

0

鑑於整數的列表,你可以這樣做:

  • 轉換t字符串的OA列表
  • 串聯使用連接
  • 拆分列表中一半
  • 使用int轉換爲二進制

在長形:

x = [1,0,0,1,1,0,0,0] 
# The following two lines are equivalent - choose the most readable 
strings = ''.join(map(str,x)) # Using map 
strings = ''.join(str(z) for z in x) # Using a list loop 
print(strings) 
strings1 = strings[:4] # First four 
strings2 = strings[-4:] # Last four 
bin1 = int(strings1) 
bin2 = int(strings2) 
# int function takes a second argument for base 
int1 = int(strings1,2) 
int2 = int(strings2,2) 

在一個行:

int1 = int(''.join(map(str,x))[:4],2) 
int2 = int(''.join(map(str,x))[-4:],2) 

適合您的問題,其中包含一個列表的列表:)無效字面INT(:

# For each element l of list x (l being a list) 
for l in x: 
    for z in l: 
     int1 = int(''.join(map(str,z))[:4],2) 
     int2 = int(''.join(map(str,z))[-4:],2) 
     print(int1) 
     print(int2) 
+0

感謝你爲一個偉大的方式,但如果我用一個numpy的數組列表中的「二進制的」我會得到這個錯誤:'ValueError異常基地2:'[1 0''任何想法@mjsqu – azeez

+0

我以另一種方式嘗試過這種方法,但我有同樣的錯誤,那爲什麼我嘗試了我在開始寫的東西! – azeez

+0

更新,它似乎numpy數組可能是列表的列表,所以我已經添加了一個額外的'for'到循環 – mjsqu

相關問題