嵌套列表(字符串)到python中的float矩阵

时间:2017-08-25 19:20:29

标签: list numpy

我想知道什么会将像12 -1 0.01 3 那样结构化的大型列表转换为类似

的数组
import numpy as nu  
list1 = ['12,-1', '0.01,3']  
pp=  nu.zeros(shape=(len (list1),2))  
for i in range (len (list1)):  
   pp[i,0]= map (float,list1[i].split(','))[0]  
   pp[i,1]= map (float,list1[i].split(','))[1]  

以下代码执行此操作,但我认为它不高效:

function open(size, parentSelector) {
        var parentElem = parentSelector ?
          angular.element($document[0].querySelector('.grid ' + parentSelector)) : undefined;

        var modalInstance = $uibModal.open({
            animation: vm.animationsEnabled,
            ariaLabelledBy: 'modal-title',
            ariaDescribedBy: 'modal-body',
            size: size,
            appendTo: parentElem,
            templateUrl: 'Views/Shared/ColSetting.html',
            resolve: {
                load: ['$q','$rootScope',function ($q, $rootScope) {
                    var loadController = "Views/Shared/ColSettingController";
                    var deferred = $q.defer();
                    require([loadController], function () {
                        deferred.resolve(items);
                        $rootScope.$apply();
                    });
                    return deferred.promise;
                }]
            }
        });

有什么建议吗?

3 个答案:

答案 0 :(得分:0)

使用numpy.split例程的解决方案:

import numpy as np

list1 = ['12,-1', '0.01,3']
result = np.split(np.array([float(i) for _ in list1 for i in _.split(',')]), 2)
print(result)

输出:

[array([ 12.,  -1.]), array([ 0.01,  3.  ])]

答案 1 :(得分:0)

np.matrix有一个字符串输入法,用来模仿MATLAB风格:

In [1269]: alist =  ['12,-1', '0.01,3']
In [1270]: np.matrix(';'.join(alist))
Out[1270]: 
matrix([[  1.20000000e+01,  -1.00000000e+00],
        [  1.00000000e-02,   3.00000000e+00]])
In [1271]: _.A
Out[1271]: 
array([[  1.20000000e+01,  -1.00000000e+00],
       [  1.00000000e-02,   3.00000000e+00]])

这很方便。我认为解析涉及类似于你所做的事情 - 几个级别的分裂。

做我们自己的分裂:

In [1273]: np.array([line.split(',') for line in alist])
Out[1273]: 
array([['12', '-1'],
       ['0.01', '3']],
      dtype='<U4')

如果我们指定dtypenp.array会将字符串转换为浮点数给我们:

In [1274]: np.array([line.split(',') for line in alist],float)
Out[1274]: 
array([[  1.20000000e+01,  -1.00000000e+00],
       [  1.00000000e-02,   3.00000000e+00]])

列表理解会创建一个列表列表:

In [1275]: [line.split(',') for line in alist]
Out[1275]: [['12', '-1'], ['0.01', '3']]

答案 2 :(得分:0)

一个好的解决方案是

import numpy as np

list1 = ['12,-1,2', '0.01,3,4','-2,3,4']
float_list = np.array([element for row in list1 for element in row.split(',')], dtype=np.float)
matrix = np.split(float_list, len(list1))
print(matrix)