目录
1 A list is a sequence
Like a string, a list is a sequence of values. In a string, the values are characters; in a list, they can be any type. The values in list are called elements or sometimes items.
列表是一列值的综合,这些值可以是任意类型,如:
[10, 20, 30, 40] 数值列表
['crunchy frog', 'ram bladder', 'lark vomit'] 字符串列表['spam', 2.0, 5, [10, 20]] 列表中包含列表
▲采用[ ] 创建列表
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print(cheeses, numbers, empty)
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
2 Lists are mutable
▲列表和字符串一样可以用[ ]取出某个或某些元素,但是列表中的元素是可以被更改的mutable
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print(numbers)
[17, 5]
▲由于列表的可变性,导致它和字符串有明显的区别
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
上述情况中,a和b虽然内容相同,但由于他们的内容时可以发生变化的,所以a和b是两个对象
▲另一种情况:
>>> a = [1, 2, 3]
>>> b = a ###将a的值赋给b,此时a和b指的是一个变量,a和b互为别名alias
>>> b is a
True
>>> b[0] = 17
>>> print(a) ###改变b时,a也发生变化
[17, 2, 3]
▲in,+,*运算符也可以运用于列表
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print(c)
[1, 2, 3, 4, 5, 6]
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
3 Traversing a list
▲方法一:for循环遍历每个列表元素,迭代变量为列表里的元素
for cheese in cheeses: ###迭代变量为列表里的元素
print(cheese)
▲方法二:for循环遍历列表的顺序,再用[ ]取出对应位置的值,迭代变量为列表的位置
for i in range(len(numbers)): ###range函数返回一个从0到n-1的列表
numbers[i] = numbers[i] * 2
4 List methods
方法 | 描述 |
---|---|
append() | 在列表的末尾添加一个元素 |
clear() | 删除列表中的所有元素 |
copy() | 返回列表的副本 |
count() | 返回具有指定值的元素数量。 |
extend() | 将列表元素(或任何可迭代的元素)添加到当前列表的末尾 |
index() | 返回具有指定值的第一个元素的索引 |
insert() | 在指定位置添加元素 |
pop() | 删除指定位置的元素 |
remove() | 删除具有指定值的项目 |
reverse() | 颠倒列表的顺序 |
sort() | 对列表进行排序 |
append adds a new element to the end of a list
append在列表后添加新元素
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print(t)
['a', 'b', 'c', 'd']
extend takes a list as an argument and appends all of the elements
extend在连接两个列表,注意作为参数的那个列表的值是不变的
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2) ###只改变t1
>>> print(t1)
['a', 'b', 'c', 'd', 'e']
>>> print(t2)
[ 'd', 'e'] ###t2不变
sort arranges the elements of the list from low to high
sort从低到高给列表排序
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print(t)
['a', 'b', 'c', 'd', 'e']
pop modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.
pop根据index删除列表中对应位置的元素,并返回该元素的值,如果index为空则删除和返回最后一个元素
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print(t)
['a', 'c']
>>> print(x)
b
If you know the element you want to remove (but not the index), you can use remove.
remove根据元素内容删除元素,且不返回值
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']
补充:del函数也可以删除列表中的元素,根据列表的index删除一个或多个元素
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print(t)
['a', 'c']
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print(t)
['a', 'f']
5 Lists and functions
>>> nums = [3, 41, 12, 9, 74, 15]
>>> print(len(nums)) ###长度
6
>>> print(max(nums)) ###最大值
74
>>> print(min(nums)) ###最小值
3
>>> print(sum(nums)) ###求和
154
>>> print(sum(nums)/len(nums)) ###平均值
25
▲示例:读取数据并求均值
numlist = list() ###创建空list
while (True):
inp = input('Enter a number: ') ###用户输入
if inp == 'done': break ###输入done时结束
value = float(inp) ###输入数据转化成浮点数
numlist.append(value) ###输入数据添加到list
average = sum(numlist) / len(numlist) ###求均值
print('Average:', average)
6 Lists and strings
To convert from a string to a list of characters, you can use list
list讲字符串转化成列表,每个元素是一个字符
>>> s = 'spam'
>>> t = list(s)
>>> print(t)
['s', 'p', 'a', 'm']
If you want to break a string into words, you can use the split method
字符串的方法split(无参数时)把字符串按空格分开,分成不同单词
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print(t)
['pining', 'for', 'the', 'fjords']
>>> print(t[2])
the
也可以按别的符号进行分割,如:
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
用join方法将列表合并成字符串:
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
▲由于list是可变的,list的方法可以直接改变原本list的值,而不是像字符串一样返回一个新的值, 许多list方法的返回值是None
>>> t1 = [1, 2]
>>> t2 = t1.append(3) ###直接修改t1,而t2不发生变化
>>> print(t1)
[1, 2, 3]
>>> print(t2)
None
7 Parsing lines
▲示例:找出文件中以From开头的句子,并提取星期,如:
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 提取Sat
fhand = open('mbox-short.txt') ###建立handle
for line in fhand: ###循环文件
line = line.rstrip() ###删除newline
if not line.startswith('From '): continue ###判断是否From 开头,否则进行下一个循环
words = line.split() ###分隔字符返回列表
print(words[2]) ###输出第三个元素