舉例講解Python中的list列表數(shù)據(jù)結(jié)構(gòu)用法
循環(huán)和列表
不管怎樣,程序會做一些重復(fù)的事情,下面我們就用for循環(huán)打印一個列表變量。做這個練習(xí)的時候你必須自己弄懂它們的含義和作用。
在使用for循環(huán)之前,我們需要一個東西保存循環(huán)的值,最好的方法是使用一個列表,列表就是按照順序保存數(shù)據(jù)的容器,不是很復(fù)雜,就是一種新的語法而已,結(jié)構(gòu)像下面這樣:
hairs = ['brown', 'blond', 'red'] eyes = ['brown', 'blue', 'green'] weights = [1, 2, 3, 4]
list以 [ 號開頭,里面的元素以 , 號分隔,像函數(shù)的參數(shù)一樣,然后以 ] 結(jié)束,python把所有這些包含在一個變量中。
下面我們來看一些list,并且循環(huán)打印它們:
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'domes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty on elements = [] # then use the range function to do 0 to 5 counts for i in range(0, 6): print "Adding %d to the list." % i # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Elements was: %d" % i
運行結(jié)果
root@he-desktop:~/mystuff# python ex32.py
This is count 1 This is count 2 This is count 3 This is count 4 This is count 5 A fruit of type: apples A fruit of type: oranges A fruit of type: pears A fruit of type: apricots I got 1 I got 'pennies' I got 2 I got 'domes' I got 3 I got 'quarters' Adding 0 to the list. Adding 1 to the list. Adding 2 to the list. Adding 3 to the list. Adding 4 to the list. Adding 5 to the list. Elements was: 0 Elements was: 1 Elements was: 2 Elements was: 3 Elements was: 4 Elements was: 5
訪問列表中的元素
List是非常有用的,前提是要知道怎么用,那么我們怎么訪問列表中的元素呢?下面看看我們怎么訪問列表的第一個元素的:
animals = ['bear', 'tiger', 'penguin', 'zebra'] bear = animals[0]
我們使用0去獲得第一個元素?這是怎么工作的呢?因為python開始一個list是從0開始的,看上去很奇怪,但是有很多好處,暫且認(rèn)為這是一個規(guī)定吧。
這就提現(xiàn)了我們用數(shù)字和程序用數(shù)字的不同。
想象一下,我們讓這四個動物進(jìn)行競速比賽,然后按照他們的名次在list排列。如果你的朋友想知道誰贏了,那么他會說:”誰是第0名?“,當(dāng)然不會,他會說:”誰是第一名?“
這里也說明了排序的重要性,沒有第一就沒有第二的說法,沒有第二就沒有第三。而且第0名也是不可能存在的,0就表示沒有。我們怎么讓沒有去贏得比賽?這不合常理。我們把這些數(shù)字叫做有序的數(shù)字,因為它們有序的區(qū)別了一些東西。
當(dāng)然,程序員不會想這些,因為他們可以從list中取出元素,對于程序員來說,上面的list就想一疊卡片。如果他們想要老虎,就取出老虎,想要斑馬就取得斑馬。想要隨機(jī)的取得任何元素的話,就要給每個元素一個地址,或者說是一個索引,最好的辦法是從0開始,然后按照順序排列,這樣我們就能隨便取元素了,即使是第0個元素。
比如說,你想要第三個動物,那么你就可以用3減去1,得出索引2,那么就可以得到第三個動物了。
記住:序號==順序1,基數(shù)==0
讓我們做一個練習(xí),通過我提供的序號和基數(shù)值寫出相應(yīng)的動物。記住,說第一,第二的時候表示序號,單單給出一個數(shù)字的時候表示基數(shù)。
animals = ['bear', 'python', 'peacock', 'kangaroo', 'whale', 'platypus']
The animal at 1. The 3rd animal. The 1st animal. The animal at 3. The 5th animal. The animal at 2. The 6th animal. The animal at 4.
回答的格式像這樣:第一個動物是在0號,它是bear。
列表操作
如果我們只知道使用list的append方法,那么我們還不是真正知道這個函數(shù)的用法,讓我們來看看它的使用方法吧。
當(dāng)我們使用mystuff.append('hello')的時候發(fā)生了一系列的事情,讓我們看看到底發(fā)生了什么:
python會先查看mystuff變量,看看是不是函數(shù)的參數(shù),或者是全局變量,反正先要找到mystuff。
當(dāng)mystuff使用 . 號的時候,會先看mystuff這個變量是什么,如果是list的話,會有很多它的方法可以使用。
使用append的時候,會去查找mystuff是不是有'append‘這個名稱,有的話就直接拿來使用。
如果append后面有圓括號,那么就知道它是一個函數(shù),像平時一樣執(zhí)行這個函數(shù)就好了,還會有額外的參數(shù)。
這個額外的參數(shù)就是mystuff,奇怪吧,但是python就是這樣做的,最后函數(shù)是這樣的:append(mystuff, 'hello')。
大多數(shù)情況下你不必知道這是怎么回事,但是在你遇到下面這個錯誤的時候就有幫助了:
root@he-desktop:~# python Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) [GCC 4.4.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.
>>> class Thing(object): ... def test(hi): ... print "hi" ... >>> a = Thing() >>> a.test("hello") Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: test() takes exactly 1 argument (2 given) >>>
下面的練習(xí)是將字符串和列表混合起來,看看我們能不能找出一些好玩的。
ten_things = "Apples Oranges Crows Telephone Light Sugar" print "Wait there's not 10 things in that list, let's fix that." stuff = ten_things.split(" ") more_stuff = ["Day", "Night", "Song", "Frisbee", "Corn", "Banana", "Girl", "Boy"] while len(stuff) != 10: next_one = more_stuff.pop() print "Adding:", next_one stuff.append(next_one) print "Thing's %d items now." % len(stuff) print "There we go:", stuff print "Let's do some things with stuff." print stuff[1] print stuff[-1] # print stuff.pop() print ' '.join(stuff) print '#'.join(stuff[3:5])
運行結(jié)果
root@he-desktop:~/mystuff# python ex38.py
Wait there's not 10 things in that list, let's fix that. Adding: Boy Thing's 7 items now. Adding: Girl Thing's 8 items now. Adding: Banana Thing's 9 items now. Adding: Corn Thing's 10 items now. There we go: ['Apples', 'Oranges', 'Crows', 'Telephone', 'Light', 'Sugar', 'Boy', 'Girl', 'Banana', 'Corn'] Let's do some things with stuff. Oranges Corn Corn Apples Oranges Crows Telephone Light Sugar Boy Girl Banana Telephone#Light
相關(guān)文章
詳解pytest分布式執(zhí)行插件?pytest-xdist?的高級用法
這篇文章主要介紹了pytest分布式執(zhí)行插件?pytest-xdist?的高級用法,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08超詳細(xì)PyTorch實現(xiàn)手寫數(shù)字識別器的示例代碼
這篇文章主要介紹了超詳細(xì)PyTorch實現(xiàn)手寫數(shù)字識別器的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03Python編程實現(xiàn)雙擊更新所有已安裝python模塊的方法
這篇文章主要介紹了Python編程實現(xiàn)雙擊更新所有已安裝python模塊的方法,涉及Python針對模塊操作命令的相關(guān)封裝與調(diào)用技巧,需要的朋友可以參考下2017-06-06SELENIUM自動化模擬鍵盤快捷鍵操作實現(xiàn)解析
這篇文章主要介紹了SELENIUM自動化模擬鍵盤快捷鍵操作實現(xiàn)解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10numpy.ndarray 實現(xiàn)對特定行或列取值
今天小編就為大家分享一篇numpy.ndarray 實現(xiàn)對特定行或列取值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12