如何獲取列表元素:
列表的每一個元素都有一個地址,改地址稱爲“索引(index)”,索引是以“0”開頭,這類數字被稱爲“基數”,意味着你可以抓取任意元素。
我們日常使用的計數,是從1開始的,而編程語言的計數,是從0開始的。也就是說,列表中最靠前的元素是第0號元素,而不是我們日常生活中的第1號元素。
使用下標索引來訪問列表中的值,同樣你也可以使用方括號的形式截取字符,如下所示:
list1 = ['Google', 'baidu', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print ("list1[0]: ", list1[0])
print ("list2[1:5]: ", list2[1:5])
理解基數與序數後,我們做一下練習:
animals = ['bear','python','peacock','kangaroo','whale','platypus']
print("The animal at 1: %s" % animals[1])
print("The 3rd animal: %s" % animals[2])
print("The 1st animal: %s" % animals[0])
print("The animal at 3: %s" % animals[3])
print("The 5th animal: %s" % animals[4])
print("The animal at 2: %s" % animals[2])
print("The 6th animal: %s" % animals[5])
print("The animal at 4: %s" % animals[4])