Then Peter came to him and said,"Lord, how many times must I forgive my brother who sins against me? As many as seven times?" Jesus said to him,"Not seven times, I tell you, but seventy-seven times?" (MATTHEW 18:21-22)

回顾列表和字符串

列表和字符串两种类型的对象,有不少相似的地方,也有很大的区别。

本讲对她们做个简要比较,同时也是对前面有关两者的知识复习一下,所谓“温故而知新”。

相同点

都是序列

不管是组成列表的元素,还是组成字符串的字符,都可以从左向右,依次用0, 1, 2, ...这样的方式建立索引。而要得到一个或多个元素,可以使用切片。

关于序列的基本操作,对两者都适用。

例如:

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

区别

列表和字符串的最大区别是:列表是可以改变的,字符串是不可变。这个怎么理解呢?

首先看对列表的这些操作,其根源在于列表可以进行修改,即列表是可变的。

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

如果要修改一个str,不得不这样。

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

其实,在这种做法中,相当于重新生成了一个str。

多维list

这个也应该算是两者的区别了,虽然有点牵强。

在字符串里面的每个元素只能是字符;在列表中,元素可以是任何类型的数据。前面见的多是数字或者字符,其实还可以这样:

>>> 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被当成一个元素对待。

列表和字符串转化

符合某些条件的情况下,可以实现列表和字符串之间的转化。会使用到split()join(),对这两个函数,已经不陌生了,在前面字符串部分已经见过。

一回生,二回熟,这次再见面,特别是在已经学习了列表的基础上,应该有更深刻的理解。

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'

读者是否感到新奇,对于join()函数,其格式是"sep".join(list),不是list.join(sep)。其实,join()是字符串的方法,不是列表的方法。

>>> help(str.join)
Help on method_descriptor:

join(...)
    S.join(iterable) -> str

    Return a string which is the concatenation of the strings in the
    iterable.  The separator between elements is S.

不过,能传入join()的对象,或者说参数的值,也是有条件的。下面的就不行。

>>> a = [1,2,3,'a','b','c']
>>> "+".join(a)
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    "+".join(a)
TypeError: sequence item 0: expected str instance, int found

“列表是苦力”,但是暂且让它干这么多。因为更多类型的对象依次登场,先让它到后台。


总目录   |   上节:列表(3)   |   下节:元组

如果你认为有必要打赏我,请通过支付宝:[email protected],不胜感激。

results matching ""

    No results matching ""