2012-10-10 59 views
2

我有一個二維數組獲取值?例如,我想print (name + " " + type)並獲得Python從二維數組

獵槍武器

我無法找到一個方法來做到這一點。不知何故print list[2][1]輸出什麼,甚至沒有錯誤。

+1

如果你命名你的結構「列表」,小心,因爲列表是一個保留字在Python中。 – sahhhm

+2

「我有一個2D陣列」不,你沒有,你有嵌套的陣列。 –

回答

6
>>> mylist = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'f 
ood'], []] 
>>> print mylist[2][1] 
weapon 

記住幾件事情,

  1. 沒有命名您的列表,list ......這是一個Python保留字
  2. 列表索引0開始。所以mylist[0]會給[]
    同樣, mylist[1][0]會給'shotgun'
  3. 考慮備用數據結構,如dictionaries
+0

如果我不打算將其他內容添加到這些列表中,將會使用字典。例如,如果我有[「霰彈槍」,「武器」,「普通」]它不再是一對:)謝謝反正 –

3

通過索引訪問適用於任何sequence(String, List, Tuple): -

>>> list1 = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []] 
>>> list1[1] 
['shotgun', 'weapon'] 
>>> print list1[1][1] 
weapon 
>>> print ' '.join(list1[1]) 
shotgun weapon 
>>> 

您可以使用名單上加入,得到串出名單..

+0

爲什麼選擇投票?我應該從downvoter這裏得到一個評論? –

0
array = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []] 
print " ".join(array[1]) 

切片放入數組與[1],然後加入數組的內容使用' '.join()

0
In [80]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []] 
Out[80]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []] 

In [81]: a = [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []] 

In [82]: a[1] 
Out[82]: ['shotgun', 'weapon'] 

In [83]: a[2][1] 
Out[83]: 'weapon' 

爲了讓所有的列表元素,你應該使用如下循環。

In [89]: a 
Out[89]: [[], ['shotgun', 'weapon'], ['pistol', 'weapon'], ['cheesecake', 'food'], []] 

In [90]: for item in a: 
    print " ".join(item) 
    ....:  

shotgun weapon 
pistol weapon 
cheesecake food