簡體   English   中英

在python中創建數字的二進制表示形式的矩陣

[英]create a matrix of binary representation of numbers in python

為了在鼠尾草中編碼漢明鱈魚(基於python的編譯器),我需要創建一個矩陣,其中每一列都是數字的二進制表示,例如Hamming(3),矩陣應如下所示

0  0  0  1  1  1  1
0  1  1  0  0  1  1
1  0  1  0  1  0  1

這是從1到7的數字的二進制表示形式。所以,到目前為止,我所做的就是將任何給定的數字轉換為二進制表示形式:我做了這個小功能,它需要兩個值n和r以及n代表r個位

binrep(n,r)
    x=n
    L=[]
    LL=[]
    while (n>0):
        a=int(float(n%2))
        L.append(a)
        n=(n-a)/2
    while (len(L)<r):
        L.append(0)
    #print(L)
    LL=L[::-1]
    return LL

所以現在我想收集我得到的所有LL,並像上面的一樣將它們放在一個大矩陣中

您只需要將所有這些二進制表示形式轉換為整數列表,將它們收集在列表列表中,然后最后對列表列表進行轉置即可獲得所需的輸出。

n = 3
binary = []
for i in range(1, 2**n):
    s = binrep(i, n)
    binary.append(map(int, s))
matrix = zip(*binary)

或在一行中: matrix = zip(*(map(int, binrep(i, n)) for i in range(1, 2**n)))

結果是

[(0, 0, 0, 1, 1, 1, 1), 
 (0, 1, 1, 0, 0, 1, 1), 
 (1, 0, 1, 0, 1, 0, 1)]

另請注意,還有其他將數字轉換為二進制的方法 ,例如,使用str.format

def binrep(n,r):
    return "{0:0{1}b}".format(n, r)

除了其他答案,還使用numpy給出答案:

import numpy as np

# we're creating the binary representation for all numbers from 0 to N-1
N = 8

# for that, we need a 1xN matrix of all the numbers
a = np.arange(N, dtype=int)[np.newaxis,:]

# we also need a log2(N)x1 matrix, for the powers of 2 on the numbers.
# floor(log(N)) is the largest component that can make up any number up to N
l = int(np.log2(N))
b = np.arange(l, dtype=int)[::-1,np.newaxis]

# This step is a bit complicated, so I'll explain it below.
print np.array(a & 2**b > 0, dtype=int)

打印:

[[0 0 0 0 1 1 1 1]
 [0 0 1 1 0 0 1 1]
 [0 1 0 1 0 1 0 1]]

print np.array(a & 2**b > 0, dtype=int)

一次做幾件事。 我將其分為更簡單的步驟:

# this takes our matrix b and creates a matrix containing the powers of 2
# up to 2^log2(N) == N
# (if N is a power of 2; otherwise, up to the next one below)
powers = 2**b

# now we calculate the bit-wise and (&) for each combination from a and b.
# because a has one row, and b as one column, numpy will automatically
# broadcast all values, so the resulting array has size log2(N)xN.
u = a & powers

# this is almost what we want, but has 4's in the first row,
# 2's in the second row and 1's in the last one.
# one method of getting 1's everywhere is to divide by powers:
print u / powers

# another way is to check where u > 0, which yields an array of bools,
# which we then convert to numbers by turning it into an array of ints.
print np.array(u > 0, dtype=int)

就像提到的zoosuck一樣,我建議使用bin()函數代替您的代碼。 假設格式相似,要按順序打印它們:

L = ['10101010', '10101010']

for i in L:
    print ' '.join([j for j in i])

您可以通過類似的方式將其附加到列表或字典中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM