List
序列是Python中最基本的数据结构。序列中的每个元素都分配了一个数字,称为位置或索引。第一个索引是0,第二个是1…
Python中最常用的序列是List和Tuple;你可以对序列类型执行某些操作,包括索引、切片、添加、乘法和检查成员资格。此外,Python还有用于查找序列长度、最大和最小元素的内置函数。
List
List是Python中最通用的数据类型,仅需要用逗号分隔开列表元素,放在[]内。最重要的是List中的各项不必具有相同类型。
例:
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
获取List中的值
通过索引可以获取list的值
list1 = ['physics', 'chemistry', 1997, 2000]
list2 = [1, 2, 3, 4, 5, 6, 7 ]
print("list1[0]: ", list1[0])
print("list2[1:5]: ", list2[1:5])
执行结果
list1[0]: physics
list2[1:5]: [2, 3, 4, 5]
更新List
可以通过赋值运算符给左侧的索引来更新List元素,并且可以使用append方法向List中添加元素
例:
list = ['physics', 'chemistry', 1997, 2000]
print "Value available at index 2 : "
print(list[2])
list[2] = 2001
print("New value available at index 2 : ")
print(list[2])
执行结果
Value available at index 2 :
1997
New value available at index 2 :
2001
删除List元素
如果知道要删除的元素,可以使用del语句,如果不知道可以使用remove()方法
例:
list1 = ['physics', 'chemistry', 1997, 2000]
print(list1)
del list1[2]
print("After deleting value at index 2 : ")
print(list1)
执行结果
['physics', 'chemistry', 1997, 2000]
After deleting value at index 2 :
['physics', 'chemistry', 2000]
List基本操作
与string类似,+ *于List表示结合与重复操作,与string不同的是结果是一个新List
Python Expression | Results | Description |
---|---|---|
len([1,2,3]) | 3 | Length |
[1,2,3]+[4,5,6] | [1,2,3,4,5,6] | Concatenation |
[‘Hi!’] * 4 | [‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’] | Repetition |
3 in [1, 2, 3] | True | Membership |
for x in [1, 2, 3]: print x | 1 2 3 | Iteration |
索引、切片、矩阵
因为List是序列,因此对string适用的索引切片也可以用于List
L = ['spam', 'Spam', 'SPAM!']
Python Expression | Results | Description |
---|---|---|
L[2] | SPAM! | Offsets start at zero |
L[-2] | Spam | Negative: count from the right |
L[1:] | [‘Spam’, ‘SPAM!’] | Slicing fetches sections |
List的内置函数与方法
Sr.No. | Function with Description |
---|---|
1 | cmp(list1,list2) Compares elements of both lists |
2 | len(list) Gives the total length of the list |
3 | max(list) Returns item from the list with max value |
4 | min(list) Returns item from the list with min value |
5 | list(seq) Converts a tuple into list |
List Method
Sr.No. | Methods with Description |
---|---|
1 | list.append(obj) Appends object obj to list |
2 | list.count(obj) Returns count of how many times obj occurs in list |
3 | list.extend(seq) Appends the contents of seq to list |
4 | list.index(obj) Returns the lowest index in list that obj appears |
5 | list.insert(index,obj) Inserts object obj into list at offset index |
6 | list.pop(obj=list[-1]) Removes and returns last object or obj from list |
7 | list.remove(obj) Removes object obj from list |
8 | list.reverse() Reverses objects of list in place |
9 | list.sort(key=function,reverse=False) Sorts objects of list, key=function optional, reverse default is False |