在python中,如何将numpy.matrix [[ a b] [c d]]转换为['a','b','c','d']的字符串



在python中,如何将numpy.matrix([[a, b], [c, d]])转换为['a', 'b', 'c', 'd']字符串

给你:

import numpy as np
matrix = np.matrix([['a','b'],['c','d']])
matrix = matrix.flatten().tolist()[0]

['a', 'b', 'c', 'd']

你可以试试

arr.flatten()

arr是numpy数组,在这种情况下是您的矩阵[['a', 'b'], ['c','d']]

文档:https://numpy.org/doc/stable/reference/generated/numpy.ndarray.flatten.html

如果" numpy矩阵";只是一组字符,我根本不建议使用numpy数组。

你可以通过访问外部列表中列表的第一个[0]和第二个[1]元素并将变量重新赋值为包含4个字符的一个列表来连接两个字符串列表。

to_str = [['a','b'],['c','d']]
to_single_list = to_str[0]+to_str[1]
print(to_str)
returns: ['a', 'b', 'c', 'd']
#to change variable values to one list
import numpy as np
a=1
b=2
c=3
d=4
to_str = [[a,b],[c,d]]
to_str = to_str[0]+to_str[1]
to_str

最新更新