[Python]元组与列表的区别及内建用法
在Python中元組與列表的區別就是,列表是可變類型而元組是不可變類型。不同的問題對序列的可變性有不同的要求,Python中同時存在元組和列表是必要的。并且元組和列表時可以相互轉換的,這主要是因為list()和tuple()內建函數可以處理可迭代對象。順便提一下,Python中的可變類型為列表和字典,不可變類型為數字,字符串和元組。
因為列表是可變類型,所以列表相對于元組多了一些操作。
| s[i]=x | item?i?of?s?is replaced byx | |
| s[i:j]=t | slice of?s?fromi?toj?is replaced by the contents of the iterablet | (1) |
| dels[i:j] | same as?s[i:j]?=?[] | |
| s[i:j:k]=t | the elements of?s[i:j:k]?are replaced by those of?t | (2) |
| dels[i:j:k] | removes the elements of?s[i:j:k]?from the list | |
| s.append(x) | same as?s[len(s):len(s)]?=?[x] | (3) |
| s.extend(x) | same as?s[len(s):len(s)]?=?x | (4) |
| s.count(x) | 返回序列中x的個數,該操作元組也有 | |
| s.index(x[,i[,j]]) | return smallest?k?such thats[k]==x?andi<=k<j | (5) |
| s.insert(i,x) | same as?s[i:i]?=?[x] | |
| s.pop([i]) | same as?x?=?s[i];dels[i];returnx | (6) |
| s.remove(x) | same as?del?s[s.index(x)] | |
| s.reverse() | reverses the items of?s?in place | |
| s.sort([func[,key[,reverse]]]) | sort the items of?s?in place | (7) |
Notes:
1.t 必須可迭代
2.t?與被替代部分的長度必須相等
3.在列表末尾添加元素,無論元素類型,當做單個元素來處理。
4.在列表末尾延長列表,x必須可迭代。append與extend的區別如下程序所示:
[python]?view plaincopy
5.當x不在list中時引發ValueError異常。i,j為可選參數,表示起始與結束位置。
6.只有對列和數組有pop操作,i的默認值是-1,也就是說默認情況下彈出最后一個元素。
7.以指定的方式排序列表中額成員,如果func和key參數指定,則按照指定的方式比較各個元素,如果reverse標志設置為Ture,則列表以反序排列。
一般不該變對象的操作(比如查找類型的),元組和列表是都有的。列舉如下:
cmp(),len(),max(),min(),repr(),str(),type(),in,not in,[ ], [: ],* ,+ .
from: http://blog.csdn.net/sicofield/article/details/8616188
總結
以上是生活随笔為你收集整理的[Python]元组与列表的区别及内建用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python中的除法 整除 非整除
- 下一篇: 50个网络安全工具