国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

跟老齊學(xué)Python之有容乃大的list(3)

2020-02-23 05:49:57
字體:
供稿:網(wǎng)友

對(duì)list的操作

向list中插入一個(gè)元素

前面有一個(gè)向list中追加元素的方法,那個(gè)追加是且只能是將新元素添加在list的最后一個(gè)。如:

>>> all_users = ["qiwsir","github"]>>> all_users.append("io")>>> all_users['qiwsir', 'github', 'io']

從這個(gè)操作,就可以說明list是可以隨時(shí)改變的。這種改變的含義只它的大小即所容納元素的個(gè)數(shù)以及元素內(nèi)容,可以隨時(shí)直接修改,而不用進(jìn)行轉(zhuǎn)換。這和str有著很大的不同。對(duì)于str,就不能進(jìn)行字符的追加。請(qǐng)看官要注意比較,這也是str和list的重要區(qū)別。

與list.append(x)類似,list.insert(i,x)也是對(duì)list元素的增加。只不過是可以在任何位置增加一個(gè)元素。

我特別引導(dǎo)列為看官要通過官方文檔來理解:

代碼如下:
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).

這次就不翻譯了。如果看不懂英語,怎么了解貴國呢?一定要硬著頭皮看英語,不僅能夠?qū)W好程序,更能...(此處省略兩千字)

根據(jù)官方文檔的說明,我們做下面的實(shí)驗(yàn),請(qǐng)看官從實(shí)驗(yàn)中理解:

>>> all_users['qiwsir', 'github', 'io']>>> all_users.insert("python")   #list.insert(i,x),要求有兩個(gè)參數(shù),少了就報(bào)錯(cuò)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)>>> length5>>> all_users.insert(length,"algorithm")>>> all_users['python', 'http://', 'qiwsir', 'github', 'io', 'algorithm']

小結(jié):

list.insert(i,x),將新的元素x 插入到原list中的list[i]前面
如果i==len(list),意思是在后面追加,就等同于list.append(x)
刪除list中的元素

list中的元素,不僅能增加,還能被刪除。刪除list元素的方法有兩個(gè),它們分別是:

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,有一個(gè)習(xí)慣,就是用學(xué)習(xí)物理的方法。如果看官當(dāng)初物理沒有學(xué)好,那么一定是沒有用這種方法,或者你的老師沒有用這種教學(xué)法。這種方法就是:自己先實(shí)驗(yàn),然后總結(jié)規(guī)律。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 旅游| 贵溪市| 静海县| 东城区| 瑞金市| 文水县| 四平市| 合水县| 渑池县| 交口县| 革吉县| 怀仁县| 杭州市| 突泉县| 塘沽区| 石台县| 永济市| 宝坻区| 博乐市| 德钦县| 巴林右旗| 玛纳斯县| 凤阳县| 澄江县| 夏邑县| 长子县| 平山县| 芦山县| 华宁县| 南雄市| 遂川县| 大庆市| 杭锦后旗| 拉萨市| 伊金霍洛旗| 美姑县| 罗江县| 错那县| 乐昌市| 上林县| 丰县|