在python2.7中将列表堆叠到数组中

时间:2014-12-06 12:42:27

标签: python-2.7 numpy

我试图找出如何将多个列表添加到数组中。以下是我提出的但是它不能正常工作。

import math
import numpy as np

myList1 = [1,2,'nan']
myList2 = [3,4,5]

class myThing(object):
    def __init__(self, myLists=[]): #This could accept 1 or many lists
    self.__myVars = np.array(myLists, dtype=float)
    self.__myVars.shape = (len(myLists),3)
    self.__myVars = np.vstack(myVars)

        @property
    def myVars(self):
        return self.__myVars

foo = myThing(myList1,myList2)
print foo.myVars

blah blah...
TypeError: __init__() takes at most 2 arguments (3 given)

帮助表示赞赏

2 个答案:

答案 0 :(得分:0)

def __init__中的{p> Use *myLists允许__init__接受任意数量的参数:

def __init__(self, *myLists): #This could accept 1 or many lists

import numpy as np

myList1 = [1,2,'nan']
myList2 = [3,4,5]

class myThing(object):
    def __init__(self, *myLists): #This could accept 1 or many lists
        self.__myVars = np.array(myLists, dtype=float)

    @property
    def myVars(self):
        return self.__myVars

foo = myThing(myList1,myList2)
print foo.myVars

产量

[[  1.   2.  nan]
 [  3.   4.   5.]]

此外,在调试错误时,查看异常本身更有用。完整的回溯包括发生异常的行:

---> 20 foo = myThing(myList1,myList2)
     21 print foo.myVars

TypeError: __init__() takes at most 2 arguments (3 given)

这可以帮助我们了解造成问题的原因。

答案 1 :(得分:0)

我认为你的意思是:

def __init__(self, *myLists): #This could accept 1 or many lists