我有一个由字符串表示的3进制数字数组:
['1', '2', '10']
我希望将每个数字填充为三位数,以便每个数字占用的最大空间均为三位。
['001', '002', '010']
然后将其转换为矩阵,如下所示:
[[0, 0, 0],
[0, 0, 1],
[1, 2, 0]]
那就是将每个字符串条目转换为列向量。我尝试了旋转、转置,但不确定最佳方法是什么。
谢谢。
我有一个由字符串表示的3进制数字数组:
['1', '2', '10']
我希望将每个数字填充为三位数,以便每个数字占用的最大空间均为三位。
['001', '002', '010']
[[0, 0, 0],
[0, 0, 1],
[1, 2, 0]]
lst = ['1', '2', '10']
result = list(zip(*(map(int, i.zfill(3)) for i in lst)))
numpy
数组:import numpy as np
arr = np.array(result)
# array([[0, 0, 0],
# [0, 0, 1],
# [1, 2, 0]])
str.zfill
可以填充零,然后使用np.dstack
将其转换为期望的格式:In [106]: np.dstack([list(i.zfill(3)) for i in a])[0].astype(np.int)
Out[106]:
array([[0, 0, 0],
[0, 0, 1],
[1, 2, 0]])
numpy.char
模块,该模块提供了许多字符串操作的向量化版本:>>> import numpy as np
>>>
>>> a = np.array((1,2,10),'U2')
>>> a
array(['1', '2', '10'],
dtype='<U2')
>>>
>>> b = np.char.zfill(a, 3)
>>> b
array(['001', '002', '010'],
dtype='<U3')
>>>
>>> c = b.view('U1').reshape(3, 3).T.astype(int)
>>> c
array([[0, 0, 0],
[0, 0, 1],
[1, 2, 0]])
lst = ['1', '2', '10'] # input list
outlist = [] # empty output list
for i in lst:
while len(i) <3:
i = '0'+i # add leading 0s
outlist.append(list(i)) # string converted to list and added to output list
# convert to np.array, then to integers, transpose and convert back to list:
outlist = np.array(outlist).astype(np.int).T.tolist()
print(outlist)
输出:
[[0, 0, 0], [0, 0, 1], [1, 2, 0]]