HighwayJohn HighwayJohn - 2 months ago 7
Python Question

Convert entries of an array to a list

I have numpy arrays which entries consists of either zeros or ones. For example

A = [ 0. 0. 0. 0.]
,
B= [ 0. 0. 0. 1.]
,
C= [ 0. 0. 1. 0.]
Now I want to convert them into a list:
L =['0000', '0001', '0010']
. Is there an easy way to do it?

Answer

You can convert each list to a string using join like this

def join_list(x):
    return ''.join([str(int(i)) for i in x])

A = [0, 0, 0, 0]
B = [0, 0, 0, 1]
C = [0, 0, 1, 0]

print(join_list(A))
# 0000

The you can add them all to a new list with a for loop

new_list = []
for l in [A, B, C]:
    new_list.append(join_list(l))

print(new_list)
# ['0000', '0001', '0010']