user366312
user366312

Reputation: 16896

How can I extract a column and create a vector out of them?

mat = [['1', '2', '3', '4', '5'], 
       ['6', '7', '8', '9', '10'], 
       ['11', '12', '13', '14', '15']]

Suppose, I have this vector of vectors.

Say, I need to extract 2nd column of each row, convert them into binary, and then create a vector of them.

Is it possible to do it without using NumPy?

Upvotes: 1

Views: 49

Answers (2)

usr_lal123
usr_lal123

Reputation: 838

Yes. This is achievable with the following code :

mat = [['1', '2', '3', '4', '5'], 
       ['6', '7', '8', '9', '10'], 
       ['11', '12', '13', '14', '15']]

def decimalToBinary(n):
    return bin(n).replace("0b", "")
new_vect = []
for m in mat:
    m = int(m[1])
    new_vect.append(decimalToBinary(m))
print (new_vect)

Hope this is expected

['10', '111', '1100']

Upvotes: 1

Andy Pavlov
Andy Pavlov

Reputation: 316

Use zip for transpose list and make loop with enumerate and filter by id with bin().

mat = [['1', '2', '3', '4', '5'],
       ['6', '7', '8', '9', '10'],
       ['11', '12', '13', '14', '15']]

vec = [[bin(int(r)) for r in row] for idx, row in enumerate(zip(*mat)) if idx == 1][0]
print(vec) # ['0b10', '0b111', '0b1100']

Upvotes: 1

Related Questions