列表(List) 是 Python 中最基本的数据结构,与 C 中的数组类似

创建列表

使用中括号 [] 将各个元素括起来即可,元素类型可不相同

1
2
3
4
list1 = ['Google', 'Runoob', 1997, 2000]
list2 = [1, 2, 3, 4, 5 ]
list3 = ["a", "b", "c", "d"]
list4 = ['red', 'green', 'blue', 'yellow', 'white']

访问列表中的值

索引

列表的索引和切片与字符串的一样

使用 列表[下标] 来索引单个元素

list ‘red’ ‘green’ ‘blue’ ‘yellow’ ‘white’
从前往后数 0 1 2 3 4
从后往前数 -5 -4 -3 -2 -1
1
2
3
4
5
6
7
list = ['red', 'green', 'blue', 'yellow', 'white']
print( list[0] ) # red
print( list[1] ) # green
print( list[2] ) # blue
print( list[-1] ) # white
print( list[-2] ) # yellow
print( list[-3] ) # blue

切片

使用 变量[起始位置:终止位置:步长] 来截取部分列表

注意:

  • 左闭右开规则(顾头不顾尾)
  • 某个位置不指定的时候默认取最后或最前
  • 步长可选,默认为 1
  • 切片的时候起始位置和终止位置都超出的时候不会进行报错,但是索引会报错
1
2
3
4
print(list[0:4]) # ['red', 'green', 'blue', 'yellow']
print(list[1:-2]) # ['green', 'blue', 'yellow']
print(list[1:4:2]) # ['green', 'yellow']
print(list[-1::-1]) # ['black', 'white', 'yellow', 'blue', 'green', 'red']

For 循环遍历

1
2
3
for x in [1, 2, 3]: 
print(x, end=" ")
# 输出 1 2 3

列表操作符

组合:+

1
print([1,2,3] + [4,5,6]) # [1, 2, 3, 4, 5, 6]

重复:*

1
print([1,2,3] * 2) # [1, 2, 3, 1, 2, 3]

元素是否存在于列表中:in / not in

1
2
print (3 in [1,2,3]) # True
print (3 not in [1,2,3]) # False

列表常用方法/函数

求长

len(list)

返回列表的长度

1
2
list = ['red', 'green', 'blue', 'yellow', 'white']
print(len(list)) # 5

添加

list.append(obj)

在末尾添加新元素

1
2
3
list = ['red', 'green', 'blue', 'yellow', 'white']
list.append('black')
print(list) # ['red', 'green', 'blue', 'yellow', 'white', 'black']

list.insert(pos,obj)

使用下标在任意位置添加元素,在pos位置及其之后的元素都会往后移一位

1
2
3
list = ['red', 'green', 'blue', 'yellow', 'white']
list.insert(4,'black')
print(list) # ['red', 'green', 'blue', 'yellow', 'black', 'white']

list.extend(seq)

在末尾一次性追加另一个序列,seq可以是列表、元组、集合、字典,若为字典,则仅会将键(key)作为元素

1
2
3
4
list1 = ['red', 'green', 'blue', 'yellow']
list2 = ['white','black']
list1.extend(list2)
print(list1) # ['red', 'green', 'blue', 'yellow', 'white', 'black']

修改

使用下标修改,注意下标不能超出范围(你不能通过下标来增加新元素)

1
2
3
list = ['red', 'green', 'blue', 'yellow', 'white']
list[4] = 'black'
print(list) # ['red', 'green', 'blue', 'yellow', 'black']

删除

del list[pos]

使用del语句根据删除元素,可以使用索引,也可以使用切片

1
2
3
4
5
list = ['red', 'green', 'blue', 'yellow', 'white']
del list[2]
print(list) # ['red', 'green', 'yellow', 'white']
del list[0:2]
print(list) # ['yellow', 'white']

list.pop(pos)

删除的同时弹出元素,默认为最后一个

1
2
3
list = ['red', 'green', 'blue', 'yellow']
print(list.pop()) # yellow
print(list) # ['red', 'green', 'blue']

list.remove(obj)

移除列表中某个值的第一个匹配项

1
2
3
list = ['red', 'green', 'blue', 'yellow']
list.remove('blue')
print(list) # ['red', 'green', 'yellow']

配合while循环可以删除所有匹配项

1
2
3
4
list = ['blue', 'red',  'blue', 'green', 'blue', 'yellow', 'blue']
while 'blue' in list:
list.remove('blue')
print(list) # ['red', 'green', 'yellow']

list.clear()

清空列表

1
2
3
list = ['red', 'green', 'blue', 'yellow', 'white']
list.clear()
print(list) # []

查找

list.index(obj[,start[,end]])

返回查找对象的第一个索引位置,如果找不到则会报错

1
2
list = ['red', 'green', 'blue', 'yellow']
print(list.index('blue')) # 2

max/min(list)

查找列表中的最大(小)值,全数字比较数字大小,全字符串依次比较 ASCII 大小,混杂则无法比较

1
2
3
list = ['red', 'green', 'blue', 'yellow']
print(max(list)) # yellow
print(min(list)) # blue

计数

list.count(obj)

如字面义,统计元素出现次数

1
2
list = ['red', 'green', 'blue', 'yellow', 'blue']
print(list.count('blue')) # 2

排序

list.sort([key=func][,reverse=True])

默认为从小到大,添加 reverse=True 可以反转,可添加 key=func 自定义关键词

1
2
3
4
5
def myFunc(e):
return len(e)
list = ['red', 'green', 'blue', 'yellow', 'blue']
list.sort(key=myFunc,reverse=True)
print(list)

但是仅靠 key=func 不足以满足更为复杂的需求,例如在 C++ 中,经常要给结构体先按变量 A 排序,再按变量 B 排序

这时就要引入 functools 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
import functools

def myFunc(str1, str2):
if len(str1) != len(str2):
return len(str1) - len(str2)
elif str1 > str2:
return 1
else:
return -1

list = ['red', 'green', 'blue', 'yellow', 'white', 'black']
list.sort(key=functools.cmp_to_key(myFunc))
print(list) # ['red', 'blue', 'black', 'green', 'white', 'yellow']

注意,与 C++ 中 sort(a,a+6,myFunc); 不同,自定义函数返回的不是 bool 值,而是正负数

相关阅读:排序指南python3 为什么取消了sort方法中的cmp参数?

list.sorted([key=func][,reverse=True])

list.sort() 基本相同,但这个方法不会更改原列表,只会返回一个排序好的列表

反转

list.reverse()

会对列表的元素进行反向排序,该方法没有返回值

1
2
3
list = ['red', 'green', 'blue', 'yellow', 'white']
list.reverse()
print(list) # ['white', 'yellow', 'blue', 'green', 'red']

转换

list(seq)

将元组或字符串转换为列表(元组在下一篇

1
2
list = list("HelloWorld")
print(list) # ['H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd']

嵌套列表

列表之间允许嵌套

1
2
3
4
list1 = [1,2,3]
list2 = [4,5,6]
list1.append(list2)
print(list1) # [1, 2, 3, [4, 5, 6]]

引用或不引用

在前面的嵌套操作中, list1 中嵌套了一个 list2 ,当 list2 发生变化时, list1 也会跟着变化

1
2
3
4
5
list1=[1,2,3]
list2=[4,5,6]
list1.append(list2)
list2.append(7)
print(list1) # [1, 2, 3, [4, 5, 6, 7]]

又或者,再创建一个 list3 ,并把 list2 赋值给 list3 ,当 list2 发生变化时, list3 也会跟着变化

1
2
3
4
list3 = list2
print(list3) # [4, 5, 6, 7]
list2.append(8)
print(list3) # [4, 5, 6, 7, 8]

这就是引用,在某些场景下,这也不失为一个好功能,但有时你会想避免出现这样的状况,有下面几种解决方法:

  • 使用切片

    1
    2
    3
    4
    list4 = list2[:]
    print(list4) # [4, 5, 6, 7, 8]
    list2.append(9)
    print(list4) # [4, 5, 6, 7, 8]
  • copy() 方法

    1
    2
    3
    4
    list4 = list2.copy()
    print(list4) # [4, 5, 6, 7, 8]
    list2.append(9)
    print(list4) # [4, 5, 6, 7, 8]
  • 深拷贝

    1
    2
    3
    4
    5
    import copy
    list4 = copy.deepcopy(list2)
    print(list4) # [4, 5, 6, 7, 8]
    list2.append(9)
    print(list4) # [4, 5, 6, 7, 8]

数字列表

range() 函数

使用 range() 可以轻松地生成一系列数

1
2
for value in range(1, 5):
print(value,end=" ")

就像你猜想的一样,它是左闭右开的,所以并不会输出 5

使用 range() 创建数组列表

配合 list() ,可以将 range() 的结果转换为列表

1
2
numbers = list(range(1, 6))
print(numbers) [1, 2, 3, 4, 5]

使用 range() 时,还可以指定步长

例如这里打印 1~10 的偶数

1
2
numbers = list(range(2, 11, 2))
print(numbers) # [2, 4, 6, 8, 10]

使用 range() 能够创建几乎所有的数集,例如创建一个列表,包含 1~10 的平方

1
2
3
4
squares = []
for value in range(1, 11):
squares.append(value**2)
print(squares) # [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

对数字列表执行简单的统计

你可以轻松地找出数字列表中的最大值、最小值和总和

1
2
3
4
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print(min(digits)) # 0
print(max(digits)) # 9
print(sum(digits)) # 45