文章目录
列表数据类型
"列表“是一个值,它包含多个字构成的序列。术语"列表值"指的是列表本身(它作为一个值,可以保存在变量中,或传递给函数,像其他所有值一样),而不是指列表值之内的那些值。列表值看起来像这趟:['cat','bat','rat','elephant']
。就像字符串值用引号来标记字符串的起止一样,列表用左方括号开始,右方括号结束,即[]
。列表中的值也称为“表项”。表项用逗号分隔。例如,在交互式环境中输入以下代码:
>>> [1,2,3]
[1, 2, 3]
>>> ['cat','bat','rat','elephant']
['cat', 'bat', 'rat', 'elephant']
>>> ['hello',3.1415,True,None,42]
['hello', 3.1415, True, None, 42]
>>> spam = ['cat','bat','rat','elephant']
>>> spam
['cat', 'bat', 'rat', 'elephant']
>>>
spam 变量仍然只被赋予一个值:列表值。但列表值本身包含多个值。[]
是一个空列表,不包含任何值,类似于空字符串''
。
用下表取得列表中的单个值
假定列表['cat','bat','rat','elephant']
保存在名为 spam 的变量中。那么 spam[0] 的值为 ‘cat’,spam[1] 的值为 ‘bat’,以此类推。列表后面方括号内的整数被称为“下标”。列表中第一个值的下标是 0,第二个值的下标是 2,以此类推。
例如,在交互式环境中输入以下表达式。开始将列表赋给变量 spam。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[0]
'cat'
>>> spam[1]
'bat'
>>> spam[2]
'rat'
>>> spam[3]
'elephant'
>>> ['cat','bat','rat','elephant'][3]
'elephant'
>>> 'Hello ' + spam[0]
'Hello cat'
>>> 'The ' + spam[1] + ' ate the ' + spam[0] + '.'
'The bat ate the cat.'
如果使用的下标超出了列表中值的个数,python 将给出 IndexError
出错信息。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[10000]
Traceback (most recent call last):
File "<pyshell#15>", line 1, in <module>
spam[10000]
IndexError: list index out of range
下标只能是整数,不能是浮点数。下面的例子将导致 TypeError
错误。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[1]
'bat'
>>> spam[1.0]
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
spam[1.0]
TypeError: list indices must be integers or slices, not float
>>> spam[int(1.0)]
'bat'
列表也可以包含其他列表值。这些列表的列表中的值,可以通过多重下标来访问。
>>> spam = [['cat','bat'],[10,20,30,40,50]]
>>> spam[0]
['cat', 'bat']
>>> spam[0][1]
'bat'
>>> spam[1][4]
50
负数下标
虽然下标从 0 开始并向上增长,但也可以用负整数作为下标。整数值 -1 指的是列表中的最后一个下标,-2 指的是列表中倒数第二个下标,以此类推。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[-1]
'elephant'
>>> spam[-3]
'bat'
>>> 'The ' + spam[-1] + ' is afarid of the ' + spam[-3] + '.'
'The elephant is afarid of the bat.'
利用切片取得子列表
就像下标可以从列表中取得单个值一样,“切片”可以从列表中取得多个值,结果就是一个新列表。切片输入在一对方括号中,像下标一样,但它有两个冒号分隔的整数。
在一个切片中,第一个整数是切片开始处的下标,第二个整数是切片结束后的下标。切片向上增长,直到第二个下标的值,但不包括它。 切片求值为一个新的列表值。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[0:4]
['cat', 'bat', 'rat', 'elephant']
>>> spam[1:3]
['bat', 'rat']
>>> spam[0:-1]
['cat', 'bat', 'rat']
你可以省略切片中冒号两边的一个下标或两个下标。省略第一个下标相当于使用 0,或列表的开始。省略第二个下标相当于使用列表的长度,意味着切片直到列表的末尾。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[:2]
['cat', 'bat']
>>> spam[1:]
['bat', 'rat', 'elephant']
>>> spam[:]
['cat', 'bat', 'rat', 'elephant']
用 len() 取得列表的长度
len() 函数将返回传递给它的列表中值的个数,就像它能计算字符串中字符的个数一样。
>>> spam = ['cat','bat','rat','elephant']
>>> len(spam)
4
用下标改变列表中的值
一般情况下,赋值语句左边是一个变量名,就像 spam = 4
。但是,也可以使用列表的下标来改变下标处的值。例如,spam[1] = ‘aardvark’ 意味着将列表 spam 下标 1 处的值赋值为字符串 ‘aardvark’。
>>> spam = ['cat','bat','rat','elephant']
>>> spam[1] = 'aardvark'
>>> spam
['cat', 'aardvark', 'rat', 'elephant']
>>> spam[2] = spam[1]
>>> spam
['cat', 'aardvark', 'aardvark', 'elephant']
>>> spam[-1] = 12345
>>> spam
['cat', 'aardvark', 'aardvark', 12345]
列表连接和列表复制
+ 操作符可以连接两个列表,得到一个新列表,就像它将两个字符串合并成一个新字符串一样。
>>> [1,2,3] + ['A','B','C']
[1, 2, 3, 'A', 'B', 'C']
>>> ['X','Y','Z'] * 3
['X', 'Y', 'Z', 'X', 'Y', 'Z', 'X', 'Y', 'Z']
>>> spam = [1,2,3]
>>> spam = spam + ['A','B','C']
用 del 语句从列表中删除值
del 语句将删除列表中下标处的值,表中被删除值后面的所有值,都将向前移动一个下标。
>>> spam = ['cat','bat','rat','elephant']
>>> del spam[2]
>>> spam
['cat', 'bat', 'elephant']
>>> del spam[2]
>>> spam
['cat', 'bat']
使用列表
catNames = []
while True:
print('Enter the name of cat ' + str(len(catNames) + 1) +
' (Or enter nothing to stop.):')
name = input()
if name == '':
break
catNames = catNames + [name] #list concatenation
print('The cat names are:')
for name in catNames:
print(' ' + name)
运行结果如下:
Enter the name of cat 1 (Or enter nothing to stop.):
Zophie
Enter the name of cat 2 (Or enter nothing to stop.):
Pooka
Enter the name of cat 3 (Or enter nothing to stop.):
Simon
Enter the name of cat 4 (Or enter nothing to stop.):
Lady Macbeth
Enter the name of cat 5 (Or enter nothing to stop.):
Fat-tail
Enter the name of cat 6 (Or enter nothing to stop.):
Mias Cleo
Enter the name of cat 7 (Or enter nothing to stop.):
The cat names are:
Zophie
Pooka
Simon
Lady Macbeth
Fat-tail
Mias Cleo
列表用于循环
从技术上说,循环是针对一个列表或类似列表中的每个值,重复地执行代码块。例如,如果执行以下代码:
for i in range(4):
print(i)
程序的输出将是:
0
1
2
3
这是因为 range(4) 的返回值是类似列表的值。python 认为它类似于 [0,1,2,3]。
下面的程序和前面的程序输出相同:
for i in [0, 1, 2, 3]:
print(i)
一个常见的 python 技巧,是在 for 循环中使用 range(len(someList))
,迭代列表的每一个下标。
supplies = ['pens', 'staplers', 'flame-throwers', 'binders']
for i in range(len(supplies)):
print('Index ' + str(i) + ' in supplies is: ' + supplies[i])
输出结果如下:
Index 0 in supplies is: pens
Index 1 in supplies is: staplers
Index 2 in supplies is: flame-throwers
Index 3 in supplies is: binders
in 和 not in 操作符
利用 in 和 not in 操作符,可以确定一个值是否在列表中。像其他操作符一样,in 和 not in 用在表达式中,连接两个值:一个要在列表中查找的值,以及待查找的列表。这些表达式将求值为布尔值。
>>> 'howdy' in ['hello', 'hi', 'howdy', 'heyas']
True
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> 'cat' in spam
False
>>> 'howdy' not in spam
False
>>> 'cat' not in spam
True
例如,下面的程序让用户输入一个宠物名字,然后检查该名字是否在宠物列表中。
myPets = ['Zophie', 'Pooka', 'Fat-tail']
while True:
print('Enter a pet name:')
name = input()
if name == '':
break
if name not in myPets:
print('I do not have a pet named ' + name)
else:
print(name + ' is my pet.')
print('Quit the program')
输出结果如下:
Enter a pet name:
kitty
I do not have a pet named kitty
Enter a pet name:
Zophie
Zophie is my pet.
Enter a pet name:
Quit the program
多重赋值技巧
多重赋值技巧是一种快捷方式,让你在一行代码中,用列表中的值为多个变量赋值。所以不必像这样:
>>> cat = ['fat', 'black', 'loud']
>>> size = cat[0]
>>> color = cat[1]
>>> disposition = cat[2]
而是输入下面的代码:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition = cat
变量的数目和列表的长度必须严格相等,否则 python 将给出 ValueError:
>>> cat = ['fat', 'black', 'loud']
>>> size, color, disposition, name = cat
Traceback (most recent call last):
File "<pyshell#68>", line 1, in <module>
size, color, disposition, name = cat
ValueError: not enough values to unpack (expected 4, got 3)
增强的赋值操作
在对变量赋值时,常常会用到变量本身。例如,将 42 赋给变量 spam 之后,用下面的代码让 spam 的值增加 1:
>>> spam =42
>>> spam = spam + 1
>>> spam
43
作为一种快捷方式,可以用增强的赋值操作符 +=
来完成同样的事:
>>> spam = 42
>>> spam += 1
>>> spam
43
针对 +、-、*、/、% 操作符,都有增强的赋值操作符,如下表所示:
增强的赋值语句 | 等价的赋值语句 |
---|---|
spam += 1 | spam = spam + 1 |
spam -= 1 | spam = spam - 1 |
spam *= 1 | spam = spam * 1 |
spam /= 1 | spam = spam / 1 |
spam %= 1 | spam = spam % 1 |
+= 操作符也可以完成字符串和列表的连接。*= 操作符可以完成字符串和列表的复制。
>>> spam = 'Hello'
>>> spam += ' world!'
>>> spam
'Hello world!'
>>> bacon = ['Zophie']
>>> bacon *= 3
>>> bacon
['Zophie', 'Zophie', 'Zophie']
方法
每种数据类型都有它自己的一组方法。例如,列表数据类型有一些有用的方法,用来查找、添加、删除或操作列表中的值。
用 index() 方法在列表中查找值
列表有一个 index() 方法,可以传入一个值,如果该值存在于列表中,就返回它的下标。如果该值不在列表中,python 就报 ValueError。
>>> spam = ['hello', 'hi', 'howdy', 'heyas']
>>> spam.index('hello')
0
>>> spam.index('heyas')
3
>>> spam.index('howdy howdy howdy')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
spam.index('howdy howdy howdy')
ValueError: 'howdy howdy howdy' is not in list
如果列表中存在重复的值,就返回它第一次出现的下标。
>>> spam = ['Zophie', 'Pooka', 'Fat-tail', 'Pooka']
>>> spam.index('Pooka')
1
用 append() 和 insert() 方法在列表中添加值
类似列表的类型:字符串和元组
列表并不是唯一标识序列值的数据类型。例如,字符串和列表实际上很相似,只要你认为字符串是单个文本字符的列表。对列表的许多操作,也可以作用于字符串:按下标取值、切片、用于 for 循环、用于 len(),以及用于 in 和 not in 操作符。
>>> name = 'Zophie'
>>> name[0]
'Z'
>>> name[-2]
'i'
>>> name[0:4]
'Zoph'
>>> 'Zo' in name
True
>>> 'z' in name
False
>>> 'p' not in name
False
>>> for i in name:
print('* * * ' + i + ' * * *')
* * * Z * * *
* * * o * * *
* * * p * * *
* * * h * * *
* * * i * * *
* * * e * * *
>>> len(name)
6
可变和不可变数据类型
但列表和字符串在一个重要的方面是不同的。列表是“可变的”数据类型,它的值可以增加、删除或改变。但是,字符串是“不可变的”,它不能被更改。
尝试对字符串中一个字符重新赋值,将导致 TypeError
错误。
>>> None == spam
True
>>> name = 'Zophie a cat'
>>> name[7] = 'b'
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
name[7] = 'b'
TypeError: 'str' object does not support item assignment
“改变”一个字符串的正确方式,是使用切片和连接。
>>> name = 'Zophie a cat'
>>> newName = name[0:7] + 'the' + name[8:]
>>> name
'Zophie a cat'
>>> newName
'Zophie the cat'
元组数据类型
除了两个方面,元组数据类型几乎与列表数据类型一样。
首先,元组输入输入时使用圆括号()
,而不是方括号。
>>> eggs = ('hello', 42, 0.5)
>>> eggs[0]
'hello'
>>> eggs[1:3]
(42, 0.5)
>>> len(eggs)
3
元组和列表的主要区别还在于,元组像字符串一样,是不可变的。
>>> eggs = ('hello', 42, 0.5)
>>> eggs[1] = 99
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment