現在是講lis的第三章了。俗話說,事不過三,不知道在開頭,我也不知道這一講是不是能夠把基礎的list知識講完呢。哈哈。其實如果真正寫文章,會在寫完之后把這句話刪掉的。而我則是完全像跟看官聊天一樣,就不刪除了。
繼續。
## 對list的操作
### 向list中插入一個元素
前面有一個向list中追加元素的方法,那個追加是且只能是將新元素添加在list的最后一個。如:
~~~
>>> all_users = ["qiwsir","github"]
>>> all_users.append("io")
>>> all_users
['qiwsir', 'github', 'io']
~~~
從這個操作,就可以說明list是可以隨時改變的。這種改變的含義只它的大小即所容納元素的個數以及元素內容,可以隨時直接修改,而不用進行轉換。這和str有著很大的不同。對于str,就不能進行字符的追加。請看官要注意比較,這也是str和list的重要區別。
與list.append(x)類似,list.insert(i,x)也是對list元素的增加。只不過是可以在任何位置增加一個元素。
我特別引導列為看官要通過[官方文檔來理解](https://docs.python.org/2/tutorial/datastructures.html):
> list.insert(i, x)
>
> > Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
這次就不翻譯了。如果看不懂英語,怎么了解貴國呢?一定要硬著頭皮看英語,不僅能夠學好程序,更能...(此處省略兩千字)
根據官方文檔的說明,我們做下面的實驗,請看官從實驗中理解:
~~~
>>> all_users
['qiwsir', 'github', 'io']
>>> all_users.insert("python") #list.insert(i,x),要求有兩個參數,少了就報錯
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: insert() takes exactly 2 arguments (1 given)
>>> all_users.insert(0,"python")
>>> all_users
['python', 'qiwsir', 'github', 'io']
>>> all_users.insert(1,"http://")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io']
>>> length = len(all_users)
>>> length
5
>>> all_users.insert(length,"algorithm")
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']
~~~
小結:
* list.insert(i,x),將新的元素x 插入到原list中的list[i]前面
* 如果i==len(list),意思是在后面追加,就等同于list.append(x)
### 刪除list中的元素
list中的元素,不僅能增加,還能被刪除。刪除list元素的方法有兩個,它們分別是:
> list.remove(x)
>
> > Remove the first item from the list whose value is x. It is an error if there is no such item.
>
> list.pop([i])
>
> > Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.)
我這里講授python,有一個習慣,就是用學習物理的方法。如果看官當初物理沒有學好,那么一定是沒有用這種方法,或者你的老師沒有用這種教學法。這種方法就是:自己先實驗,然后總結規律。
先實驗list.remove(x),注意看上面的描述。這是一個能夠刪除list元素的方法,同時上面說明告訴我們,如果x沒有在list中,會報錯。
~~~
>>> all_users
['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']
>>> all_users.remove("http://")
>>> all_users #的確是把"http://"刪除了
['python', 'qiwsir', 'github', 'io', 'algorithm']
>>> all_users.remove("tianchao") #原list中沒有“tianchao”,要刪除,就報錯。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
~~~
注意兩點:
* 如果正確刪除,不會有任何反饋。沒有消息就是好消息。
* 如果所刪除的內容不在list中,就報錯。注意閱讀報錯信息:x not in list
看官是不是想到一個問題?如果能夠在刪除之前,先判斷一下這個元素是不是在list中,在就刪,不在就不刪,不是更智能嗎?
如果看官想到這里,就是在編程的旅程上一進步。python的確讓我們這么做。
~~~
>>> all_users
['python', 'qiwsir', 'github', 'io', 'algorithm']
>>> "python" in all_users #這里用in來判斷一個元素是否在list中,在則返回True,否則返回False
True
>>> if "python" in all_users:
... all_users.remove("python")
... print all_users
... else:
... print "'python' is not in all_users"
...
['qiwsir', 'github', 'io', 'algorithm'] #刪除了"python"元素
>>> if "python" in all_users:
... all_users.remove("python")
... print all_users
... else:
... print "'python' is not in all_users"
...
'python' is not in all_users #因為已經刪除了,所以就沒有了。
~~~
上述代碼,就是兩段小程序,我是在交互模式中運行的,相當于小實驗。
另外一個刪除list.pop([i])會怎么樣呢?看看文檔,做做實驗。
~~~
>>> all_users
['qiwsir', 'github', 'io', 'algorithm']
>>> all_users.pop() #list.pop([i]),圓括號里面是[i],表示這個序號是可選的
'algorithm' #如果不寫,就如同這個操作,默認刪除最后一個,并且將該結果返回
>>> all_users
['qiwsir', 'github', 'io']
>>> all_users.pop(1) #指定刪除編號為1的元素"github"
'github'
>>> all_users
['qiwsir', 'io']
>>> all_users.pop()
'io'
>>> all_users #只有一個元素了,該元素編號是0
['qiwsir']
>>> all_users.pop(1) #但是非要刪除編號為1的元素,結果報錯。注意看報錯信息
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: pop index out of range #刪除索引超出范圍,就是1不在list的編號范圍之內
~~~
給看官留下一個思考題,如果要向前面那樣,能不能事先判斷一下要刪除的編號是不是在list的長度范圍(用len(list)獲取長度)以內?然后進行刪除或者不刪除操作。
list是一個有意思的東西,內涵豐富。看來下一講還要繼續講list。并且可能會做一個有意思的游戲。請期待。
- 第零部分 獨上高樓,望盡天涯路
- 嘮叨一些關于Python的事情
- 為什么要開設本欄目
- 第一部分 積小流,至江海
- Python環境安裝
- 集成開發環境(IDE)
- 數的類型和四則運算
- 啰嗦的除法
- 開始真正編程
- 初識永遠強大的函數
- 玩轉字符串(1):基本概念、字符轉義、字符串連接、變量與字符串關系
- 玩轉字符串(2)
- 玩轉字符串(3)
- 眼花繚亂的運算符
- 從if開始語句的征程
- 一個免費的實驗室
- 有容乃大的list(1)
- 有容乃大的list(2)
- 有容乃大的list(3)
- 有容乃大的list(4)
- list和str比較
- 畫圈還不簡單嗎
- 再深點,更懂list
- 字典,你還記得嗎?
- 字典的操作方法
- 有點簡約的元組
- 一二三,集合了
- 集合的關系
- Python數據類型總結
- 深入變量和引用對象
- 賦值,簡單也不簡單
- 坑爹的字符編碼
- 做一個小游戲
- 不要紅頭文件(1): open, write, close
- 不要紅頭文件(2): os.stat, closed, mode, read, readlines, readline
- 第二部分 窮千里目,上一層樓
- 正規地說一句話
- print能干的事情
- 從格式化表達式到方法
- 復習if語句
- 用while來循環
- 難以想象的for
- 關于循環的小伎倆
- 讓人歡喜讓人憂的迭代
- 大話題小函數(1)
- 大話題小函數(2)
- python文檔
- 重回函數
- 變量和參數
- 總結參數的傳遞
- 傳說中的函數條規
- 關于類的基本認識
- 編寫類之一創建實例
- 編寫類之二方法
- 編寫類之三子類
- 編寫類之四再論繼承
- 命名空間
- 類的細節
- Import 模塊
- 模塊的加載
- 私有和專有
- 折騰一下目錄: os.path.<attribute>
- 第三部分 昨夜西風,亭臺誰登
- 網站的結構:網站組成、MySQL數據庫的安裝和配置、MySQL的運行
- 通過Python連接數據庫:安裝python-MySQLdb,連接MySQL
- 用Pyton操作數據庫(1):建立連接和游標,并insert and commit
- 用Python操作數據庫(2)
- 用Python操作數據庫(3)
- python開發框架:框架介紹、Tornado安裝
- Hello,第一個網頁分析:tornado網站的基本結構剖析:improt模塊、RequestHandler, HTTPServer, Application, IOLoop
- 實例分析get和post:get()通過URL得到數據和post()通過get_argument()獲取數據
- 問候世界:利用GAE建立tornado框架網站
- 使用表單和模板:tornado模板self.render和模板變量傳遞
- 模板中的語法:tornado模板中的for,if,set等語法
- 靜態文件以及一個項目框架
- 模板轉義
- 第四部分 暮然回首,燈火闌珊處
- requests庫
- 比較json/dictionary的庫
- defaultdict 模塊和 namedtuple 模塊
- 第五部分 Python備忘錄
- 基本的(字面量)值
- 運算符
- 常用的內建函數
- 擴展閱讀(來自網絡文章)
- 人生苦短,我用Python