如何解决在Python中将列表列表转换为数组类型
我有一个像这样的矩阵,想将其转换为数组进行处理。怎么做
[[25 3 0 1 0 2 1]
[ 1 21 0 0 0 0 0]
[ 0 3 18 0 0 0 0]
[ 1 0 0 35 2 0 0]
[ 0 0 0 4 27 2 0]
[ 0 0 0 0 1 27 0]
[ 1 1 0 0 0 0 34]]
我知道应该是这样的形式
[[25,3,1,2,1],[ 1,21,0],[ 0,18,35,4,27,34]]
通常我正在做的是手动将数组转换为上述形式并调用
class = np.array([[28,5,[ 6,25,8,51,[ 5,12,2],40,6,48,[ 2,51]])
解决方法
我不确定导入矩阵时采用什么格式,这是基于字符串的矩阵的解决方案。
from ast import literal_eval
s = '''
[[25 3 0 1 0 2 1]
[ 1 21 0 0 0 0 0]
[ 0 3 18 0 0 0 0]
[ 1 0 0 35 2 0 0]
[ 0 0 0 4 27 2 0]
[ 0 0 0 0 1 27 0]
[ 1 1 0 0 0 0 34]]
'''
s = s.replace(" [","[").replace("[ ","[")
s = ",".join(s.split())
ast.literal_eval(s)
# Out[12]:
# [[25,3,1,2,1],# [1,21,0],# [0,18,35,4,27,34]]
或一行:
ast.literal_eval(",".join(s.replace(" [","[").split()))
,
假设矩阵存储在字符串上,并且始终为整数,则可以执行以下操作:
import re
import numpy as np
my_list = """
[[25 3 0 1 0 2 1]
[ 1 21 0 0 0 0 0]
[ 0 3 18 0 0 0 0]
[ 1 0 0 35 2 0 0]
[ 0 0 0 4 27 2 0]
[ 0 0 0 0 1 27 0]
[ 1 1 0 0 0 0 34]]
"""
rows = []
for line in filter(len,map(str.strip,my_list.split("\n"))):
rows.append([ int(v) for v in re.findall(r"\b[0-9]+\b",line) ])
np_rows = np.array(rows)
在这种情况下,
>>> np_rows
array([[25,[ 1,[ 0,34]])