PDF版 ePub版

# 回顾 list 和 str

list 和 str 两种类型数据，有不少相似的地方，也有很大的区别。本讲对她们做个简要比较，同时也是对前面有关两者的知识复习一下，所谓“温故而知新”。

## 相同点

### 都属于序列类型的数据

>>> 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 不可变。这个怎么理解呢？

>>> 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']

>>> 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'

>>> welcome_str
'Welcome you'
>>> welcome_str[0]+"E"+welcome_str[2:]  #从新生成一个 str
'WElcome you'
>>> welcome_str                         #对原来的没有任何影响
'Welcome you'

## 多维 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 和 str 转化

### str.split()

>>>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']

### "[sep]".join(list)

join 可以说是 split 的逆运算，举例：

>>> name
['Albert', 'Ainstain']
>>> "".join(name)       #将 list 中的元素连接起来，但是没有连接符，表示一个一个紧邻着
'AlbertAinstain'
>>> ".".join(name)      #以英文的句点做为连接分隔符
'Albert.Ainstain'
>>> " ".join(name)      #以空格做为连接的分隔符
'Albert Ainstain'

>>> 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'