2013-07-10 48 views
2

Python noob here。我需要存儲一個浮點數組的數組。我這樣做,但它不工作:Python中的嵌套浮點數組

distance = [] ##declare my array 
distance.append ([]) ##add an empty array to the array 
distance[len(distance)-1].append ([0,1,2,3.5,4.2]) ## store array in array[0] 
print distance[0][1] ## this doesnt work, the array above got stored as 1 item 

回答

3

使用list.extendlist.append

extendappend之間的區別是,append追加傳遞給它,因爲它是對象。而extend期望傳遞給它的項目是一個可迭代的(列表,元組,字符串等)並將其項目追加到列表中。

使用append我們可以追加任何類型的對象;即可迭代或不可迭代。


>>> lis = [1,2,3] 
>>> lis.append(4)  #non-iterable 
>>> lis.append('foo') #iterable 
>>> lis 
[1, 2, 3, 4, 'foo'] 

extend的行爲有所不同,實際上追加從迭代到列表中的各個項目。

>>> lis = [1,2,3] 
>>> lis.extend('foo')  #string is an iterable in python 
>>> lis 
[1, 2, 3, 'f', 'o', 'o'] #extend appends individual characters to the list 
>>> lis.extend([7,8,9]) #same thing happend here 
>>> lis 
[1, 2, 3, 'f', 'o', 'o', 7, 8, 9] 
>>> lis.extend(4)   #an integer is an not iterable so you'll get an error 
TypeError: 'int' object is not iterable 

代碼

>>> distance = [[]] 
>>> distance[-1].extend ([0,1,2,3.5,4.2]) 
>>> distance 
[[0, 1, 2, 3.5, 4.2]] 

這將返回:

[[0, 1, 2, 3.5, 4.2]] 

如果你想這樣做,那麼就沒有必要append[],然後調用list.extend ,只需使用即可直接:

>>> ditance = [] ##declare my array 
>>> distance.append([0,1,2,3.5,4.2]) 
>>> distance 
[[0, 1, 2, 3.5, 4.2]] 
+0

謝謝你,非常有幫助! – fghajhe

+0

@fghajhe我已經添加了一些解釋,你可能會發現有幫助。 –

2

使用extend而不是append

distance[-1].extend([0,1,2,3.5,4.2]) 

(另請注意,distance[len(distance)-1]可寫distance[-1]

1

你也可以做到這一點(因爲你已經初始化的空列表至distance[0]):

distance[len(distance)-1] += [0,1,2,3.5,4.2] 
1

這裏是你做了什麼:

  1. 做一個列表
  2. 列表添加到列表
  3. 列表添加到列表清單。 如果你看過盜夢空間,你知道你現在有3名名單,並在第三人有一些項目是

有幾種方式來實現自己的目標:

1。

distance[len(distance)-1].extend([0,1,2,3,4,5]) #this one has been addressed elseqhere 
  1. 接下來的這個人應該最有意義給你。循環並追加到您內部列表

    for item in [0,1,2,3,4]: 
        distance[ -1 ].append(item) 
    
  2. 這最後一個是有點酷,好知道,但這裏真的間接:

    map(lambda item : distance[0].append(item), [1,2,3,4,5])