序列是 Python 中最基本的数据结构。
创建列表
创建一个列表,只要把逗号分隔的不同的数据项使用方括号括起来即可。
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white', 'black']
访问列表中的值
同字符串。
更新列表
可以通过替换与增加删除列表元素来更新列表。
list = ['Google', 'Runoob', 1997, 2000]
print ("第三个元素为 : ", list[2])
list[2] = 2001
print ("更新后的第三个元素为 : ", list[2])
list1 = ['Google', 'Runoob', 'Taobao']
list1.append('Baidu')
print ("更新后的列表 : ", list1)
第三个元素为 : 1997
更新后的第三个元素为 : 2001
更新后的列表 : ['Google', 'Runoob', 'Taobao', 'Baidu']
list = ['Google', 'Runoob', 1997, 2000]
print ("原始列表 : ", list)
del list[2]
print ("删除第三个元素 : ", list)
原始列表 : ['Google', 'Runoob', 1997, 2000]
删除第三个元素 : ['Google', 'Runoob', 2000]
脚本操作符
截取与拼接
截取
L=['Google', 'Runoob', 'Taobao']
>>>L=['Google', 'Runoob', 'Taobao']
>>> L[2]
'Taobao'
>>> L[-2]
'Runoob'
>>> L[1:]
['Runoob', 'Taobao']
>>>
拼接
>>>squares = [1, 4, 9, 16, 25]
>>> squares += [36, 49, 64, 81, 100]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>>
嵌套列表
使用嵌套列表即在列表里创建其它列表:
>>>a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'
列表比较
要先导入operator 模块:
import operator
a = [1, 2]
b = [2, 3]
c = [2, 3]
print("operator.eq(a,b): ", operator.eq(a,b))
print("operator.eq(c,b): ", operator.eq(c,b))
结果:
operator.eq(a,b): False
operator.eq(c,b): True
列表函数&方法
函数
方法
函数和方法的区别是,函数可以直接使用,而方法需要加list(列表名).