2014-12-06 34 views
0

我想解決如何將多個列表添加到數組中。以下是我想到的,但它不起作用。在python2.7中將列表堆疊到數組中

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) 

幫助理解

回答

0

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) 

這可以幫助我們瞭解導致問題的原因。

+0

感謝你和@xnx – mark 2014-12-06 12:56:03

0

我想你的意思:

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