2012-05-16 86 views
10

我有一個列表如何訪問列表元素

list = [['vegas','London'],['US','UK']] 

如何訪問該列表中的每個元素?

+5

這是一個非常基本的問題,一個讓我相信你迫切需要閱讀[Python的教程](http://docs.python.org/tutorial/)。例如,看起來你的數據結構沒有多大意義,字典可能是更好的選擇:'城市= {「拉斯維加斯」:「美國」,「倫敦」:「英國」}。 –

回答

17

我會先不叫它list,因爲這是構建在list類型中的Python構造函數的名稱。

但是,一旦你它重命名爲cities什麼的,你會怎麼做:

print(cities[0][0], cities[1][0]) 
print(cities[0][1], cities[1][1]) 
1

學習Python艱難地前34

試試這個

animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus'] 

# print "The first (1st) animal is at 0 and is a bear." 

for i in range(len(animals)): 
    print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i]) 

# "The animal at 0 is the 1st animal and is a bear." 

for i in range(len(animals)): 
    print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i]) 
+0

我不明白這是如何回答嵌套列表的問題。 –

0

遞歸解決方案打印列表中的所有項目:

def printItems(l): 
    for i in l: 
     if isinstance(i,list): 
     printItems(i) 
     else: 
     print i 


l = [['vegas','London'],['US','UK']] 
printItems(l) 
+0

這不是一個遞歸解決方案。 「我」的類型永遠不會是一個列表。這只是一個循環的解決方案,相當於: '我在l: print i' – pillravi

0

很簡單

y = [['vegas','London'],['US','UK']] 

for x in y: 
    for a in x: 
     print(a)