2012-05-07 18 views
1

在NumPy中,可以使用:作爲索引範圍的通配符來分配整個數組段。例如:需要範圍分配的數組類型

>>> (n, m) = (5,5) 
>>> a = numpy.array([[0 for i in range(m)] for j in range(n)]) 
>>> a 
array([[0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0], 
     [0, 0, 0, 0, 0]]) 

>>> for i in range(n): 
...  a[i, :] = [1 for j in range(m)] 
>>> a 
array([[1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1], 
     [1, 1, 1, 1, 1]]) 

然而,numpy.array僅持有數值數據。我需要一個可以容納任意對象的數組類型,並且可以像NumPy數組一樣尋址。我應該使用什麼?

編輯:我想這種範圍分配語法的完全靈活性,例如,這應該工作,太:

>>> a[:,1] = 42 
>>> a 
array([[ 1, 42, 1, 1, 1], 
     [ 1, 42, 1, 1, 1], 
     [ 1, 42, 1, 1, 1], 
     [ 1, 42, 1, 1, 1], 
     [ 1, 42, 1, 1, 1]]) 
+1

你只需要特定的情況下,或者是類似這樣的sufficent簡單的情況?在這種情況下,內置列表工作得很好,你只是省略了逗號。 – delnan

+0

@delnan都不。我也想用這個語法來處理更復雜的情況。 – clstaudt

回答

1

也許我失去了一些東西,但實際上持有的對象,以及數字numpy的一樣。

In [1]: import numpy 

In [2]: complex = {'field' : 'attribute'} 

In [3]: class ReallyComplex(dict): 
    ...:  pass 
    ...: 

In [4]: a = numpy.array([complex,ReallyComplex(),0,'this is a string']) 

In [5]: a 
Out[5]: array([{'field': 'attribute'}, {}, 0, this is a string], dtype=object) 
In [6]: subsection = a[2:] 

In [7]: subsection 
Out[7]: array([0, this is a string], dtype=object) 

當你把複雜的對象爲numpy的數組dtype變得object。您可以像訪問普通numpy數組一樣訪問數組的成員和切片。我並不熟悉序列化,但您可能會在該領域遇到缺點。

如果您確信numpys不是標準的Python列表,那麼維護一個對象集合的好方法就是切割python列表,使其非常類似於numpy數組。

std_list = ['this is a string', 0, {'field' : 'attribute'}] 
std_list[2:] 
+0

「numpy確實可以保存對象以及數字。」 我不知道的,因爲我想: >>> A [0,0] =無 回溯(最近最後一次通話): 文件 「」,1號線,在 類型錯誤:INT( )參數必須是一個字符串或數字,而不是'NoneType' 我想這解決了我的問題。 – clstaudt

+0

很高興能幫到你! – lukecampbell

1

如果numpy的不會做你所需要的,標準的Python列表將:

>>> (n, m) = (5,5) 
>>> 
>>> class Something: 
...  def __repr__(self): 
...   return("Something()") 
... 
>>> class SomethingElse: 
...  def __repr__(self): 
...   return("SomethingElse()") 
... 
>>> a = [[Something() for i in range(m)] for j in range(n)] 
>>> 
>>> for i in range(n): 
...  a[i] = [SomethingElse() for j in range(m)] #Use a[i][:] if you want to modify the sublist, not replace it. 
... 
>>> a 
[[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()], 
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()], 
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()], 
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()], 
[SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse(), SomethingElse()]]