list和str兩種類型數據,有不少相似的地方,也有很大的區別。本講對她們做個簡要比較,同時也是對前面有關兩者的知識復習一下,所謂“溫故而知新”。
## 相同點
### 都屬于序列類型的數據
所謂序列類型的數據,就是說它的每一個元素都可以通過指定一個編號,行話叫做“偏移量”的方式得到,而要想一次得到多個元素,可以使用切片。偏移量從0開始,總元素數減1結束。
例如:
~~~
>>> welcome_str = "Welcome you"
>>> welcome_str[0]
'W'
>>> welcome_str[1]
'e'
>>> welcome_str[len(welcome_str)-1]
'u'
>>> welcome_str[:4]
'Welc'
>>> a = "python"
>>> a*3
'pythonpythonpython'
>>> git_list = ["qiwsir","github","io"]
>>> git_list[0]
'qiwsir'
>>> git_list[len(git_list)-1]
'io'
>>> git_list[0:2]
['qiwsir', 'github']
>>> b = ['qiwsir']
>>> b*7
['qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir', 'qiwsir']
~~~
對于此類數據,下面一些操作是類似的:
~~~
>>> first = "hello,world"
>>> welcome_str
'Welcome you'
>>> first+","+welcome_str #用+號連接str
'hello,world,Welcome you'
>>> welcome_str #原來的str沒有受到影響,即上面的+號連接后從新生成了一個字符串
'Welcome you'
>>> first
'hello,world'
>>> language = ['python']
>>> git_list
['qiwsir', 'github', 'io']
>>> language + git_list #用+號連接list,得到一個新的list
['python', 'qiwsir', 'github', 'io']
>>> git_list
['qiwsir', 'github', 'io']
>>> language
['python']
>>> len(welcome_str) #得到字符數
11
>>> len(git_list) #得到元素數
3
~~~
## 區別
list和str的最大區別是:list是可以改變的,str不可變。這個怎么理解呢?
首先看對list的這些操作,其特點是在原處將list進行了修改:
~~~
>>> git_list
['qiwsir', 'github', 'io']
>>> git_list.append("python")
>>> git_list
['qiwsir', 'github', 'io', 'python']
>>> git_list[1]
'github'
>>> git_list[1] = 'github.com'
>>> git_list
['qiwsir', 'github.com', 'io', 'python']
>>> git_list.insert(1,"algorithm")
>>> git_list
['qiwsir', 'algorithm', 'github.com', 'io', 'python']
>>> git_list.pop()
'python'
>>> del git_list[1]
>>> git_list
['qiwsir', 'github.com', 'io']
~~~
以上這些操作,如果用在str上,都會報錯,比如:
~~~
>>> welcome_str
'Welcome you'
>>> welcome_str[1]='E'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>> del welcome_str[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object doesn't support item deletion
>>> welcome_str.append("E")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'
~~~
如果要修改一個str,不得不這樣。
~~~
>>> welcome_str
'Welcome you'
>>> welcome_str[0]+"E"+welcome_str[2:] #從新生成一個str
'WElcome you'
>>> welcome_str #對原來的沒有任何影響
'Welcome you'
~~~
其實,在這種做法中,相當于從新生成了一個str。
## 多維list
這個也應該算是兩者的區別了,雖然有點牽強。在str中,里面的每個元素只能是字符,在list中,元素可以是任何類型的數據。前面見的多是數字或者字符,其實還可以這樣:
~~~
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix = [[1,2,3],[4,5,6],[7,8,9]]
>>> matrix[0][1]
2
>>> mult = [[1,2,3],['a','b','c'],'d','e']
>>> mult
[[1, 2, 3], ['a', 'b', 'c'], 'd', 'e']
>>> mult[1][1]
'b'
>>> mult[2]
'd'
~~~
以上顯示了多維list以及訪問方式。在多維的情況下,里面的list也跟一個前面元素一樣對待。
## list和str轉化
### str.split()
這個內置函數實現的是將str轉化為list。其中str=""是分隔符。
在看例子之前,請看官在交互模式下做如下操作:
~~~
>>>help(str.split)
~~~
得到了對這個內置函數的完整說明。**特別強調:**這是一種非常好的學習方法
> split(...) S.split([sep [,maxsplit]]) -> list of strings
>
> Return a list of the words in the string S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result.
不管是否看懂上面這段話,都可以看例子。還是希望看官能夠理解上面的內容。
~~~
>>> line = "Hello.I am qiwsir.Welcome you."
>>> line.split(".") #以英文的句點為分隔符,得到list
['Hello', 'I am qiwsir', 'Welcome you', '']
>>> line.split(".",1) #這個1,就是表達了上文中的:If maxsplit is given, at most maxsplit splits are done.
['Hello', 'I am qiwsir.Welcome you.']
>>> name = "Albert Ainstain" #也有可能用空格來做為分隔符
>>> name.split(" ")
['Albert', 'Ainstain']
~~~
下面的例子,讓你更有點驚奇了。
~~~
>>> s = "I am, writing\npython\tbook on line" #這個字符串中有空格,逗號,換行\n,tab縮進\t 符號
>>> print s #輸出之后的樣式
I am, writing
python book on line
>>> s.split() #用split(),但是括號中不輸入任何參數
['I', 'am,', 'writing', 'python', 'book', 'on', 'line']
~~~
如果split()不輸入任何參數,顯示就是見到任何分割符號,就用其分割了。
### "[sep]".join(list)
join可以說是split的逆運算,舉例:
~~~
>>> name
['Albert', 'Ainstain']
>>> "".join(name) #將list中的元素連接起來,但是沒有連接符,表示一個一個緊鄰著
'AlbertAinstain'
>>> ".".join(name) #以英文的句點做為連接分隔符
'Albert.Ainstain'
>>> " ".join(name) #以空格做為連接的分隔符
'Albert Ainstain'
~~~
回到上面那個神奇的例子中,可以這么使用join.
~~~
>>> s = "I am, writing\npython\tbook on line"
>>> print s
I am, writing
python book on line
>>> s.split()
['I', 'am,', 'writing', 'python', 'book', 'on', 'line']
>>> " ".join(s.split()) #重新連接,不過有一點遺憾,am后面逗號還是有的。怎么去掉?
'I am, writing python book on line'
~~~
- 第零部分 獨上高樓,望盡天涯路
- 嘮叨一些關于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