从一个字符串列表中,像这样:
example_list = ['010','101']
我需要得到一个整数数组,其中每一行都是每个字符串,每个字符都在一列中,如下所示:
example_array = np.array([[0,1,0],[1,0,1]])
我试过这段代码,但它不起作用:
example_array = np.empty([2,3],dtype=int)
i = 0 ; j = 0
for string in example_list:
for bit in string:
example_array[i,j] = int(bit)
j+=1
i+=1
谁能帮帮我?我正在使用 Python 3.6。
预先感谢您的帮助!
最佳答案
如果所有字符串的长度都相同(这对于构建连续数组至关重要),则使用view
有效地分隔字符。
r = np.array(example_list)
r = r.view('<U1').reshape(*r.shape, -1).astype(int)
print(r)
array([[0, 1, 0],
[1, 0, 1]])
您也可以走列表推导路线。
r = np.array([[*map(int, list(l))] for l in example_list])
print(r)
array([[0, 1, 0],
[1, 0, 1]])
关于python - 字符串列表到整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52935916/