暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Python List列表详解

授客的知识库 2021-07-29
751

列表(List)定义

list = [value1, value2, …, valueN],其中,vaule值相同也可以不同

>>> squares = [1, 4, 9, 16, 25]

复制

嵌套列表

>>> 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'

复制

#注意,这里类似c语言二维数组的引用,类似的有如下的3维引用

>>> b = ['a', [['a', 'b', 'c'],[1, 2, 3]]]
>>> b[1][0][0]
'a'

复制

列表赋值

>>> list1 = [1, 2, 3]
>>> list2 = list1
>>> list2
[1, 2, 3]
>>> list2[0] = 4
>>> list2
[4, 2, 3]
>>> list1
[4, 2, 3]

复制

如上,需要注意的地方是,list赋值等同于“浅拷贝”,修改被赋值变量会影响“源变量”

列表元素值替换

利用索引逐个替换

>>> cubes = [1, 8, 27, 65, 125] #假设索引值为3的item值(即65)弄错了,应为64
>>> cubes[3] = 64 #替换错误值
>>> cubes
[1, 8, 27, 64, 125]

复制

注意:和字符串、元组不同,字符串和元组通过索引或切片获取的字符串的值是不可变的

利用切片批量替换

基于字符串的替换

>>> cubes = [3, 2, 1]
>>> cubes[1:2] = 'str'
>>> cubes
[3, 's', 't', 'r', 1]

复制

注意:

  1. 字符串被拆分成一个个字符,每个字符为list中的一个item
  2. 利用切片进行替换时,如果要替换的值是整数,则不能像上述那样替换,会报错,如下:
>>> cubes = [3, 2, 1]
>>> cubes[1:2] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only assign an iterable

复制

总结:如果切片范围为整个列表则替换整个列表,否则替换局部的item

基于列表的替换

>>> letters = ['a', 'b', 'c', ]
>>> letters
['a', 'b', 'c']
>>> letters[:2] = [3]
>>> letters
[3, 'c']

>>> letters = ['i','s','h','o','u','k','e']
>>> letters[1:5] = ['s', 'h', 'o', 'w'] #注意这里被替换元素不含索引值为5的元素
>>> letters
['i', 's', 'h', 'o', 'w', 'k', 'e']

>>> letters[0:7] = ['t', 'e', 's', 't']
>>> letters
['t', 'e', 's', 't']

复制

3)清空列表

>>> letters[:] = []
>>> letters
[]

复制

列表与del语句

这是一种通过给定元素(非索引值)从列表中移除元素的方式,也可用来移除列表块或清空整个列表,删除列表变量

>>> a = [-1, 1, 66.25, 333, 333, 1234.5]
>>> del a[0] #移除某个list元素
>>> a
[1, 66.25, 333, 333, 1234.5]
>>> del a[2:4] #移除list块
>>> a
[1, 66.25, 1234.5]
>>> del a[:]
>>> a
[]

复制

可以删除整个列表

>>> a = [1, 66.25, 1234.5]
>>> del a
>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

复制

List Comprehension

list comprehension主要用途是创建新的列表,形如:[expression for语句],根据for语句,对expression表达式进行计算并返回计算结果。

例1:

>>> squares = [x**2 for x in range(10)]
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

复制

等效做法

>>> squares = []
>>> for x in range(10):
... squares.append(x**2)
...
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

复制

例2:比较list,如果不相等,则混合两个list中的元素。

>>> [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y] 
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> [(x + y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
[4, 5, 5, 3, 6, 4, 7]

复制

注意:表达式一定要放在前,如上,必要时(如表达式为元组)添加括号

等效做法

>>> combs = []
>>> for x in [1, 2, 3]:
... for y in [3, 1, 4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

复制

例3:过滤列表中元素值大于0的元素

>>> vec = [-4, -2, 0, 2, 4]
>>> [x for x in vec if x > 0]
[2, 4]

复制

例4:获取元素绝对值并创建新列表

>>> vec = [-4, -2, 0, 2, 4]
>>> [abs(x) for x in vec]
[4, 2, 0, 2, 4]

复制

例5:每个元素调用方法

>>> freshfruit = ['banana', 'loganberry', 'passion fruit']
>>> [weapon.strip() for weapon in freshfruit]
['banana', 'loganberry', 'passion fruit']

复制

例6:复杂表达式和嵌套函数

>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 5)]
['3.1', '3.14', '3.142', '3.1416']

复制

嵌套List Comprehension

例子:采用list comprehension使一个由3个长度为4的列表实现的3*4矩阵,行列转置

>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
>>> matrix
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

复制

等同做法1:

>>> transposed = []
>>> for i in range(4):
... transposed.append([row[i] for row in matrix])
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

复制

等同做法2:

>>> transposed = []
>>> for i in range(4):
... # the following 3 lines implement the nested listcomp
... transposed_row = []
... for row in matrix:
... transposed_row.append(row[i])
... transposed.append(transposed_row)
...
>>> transposed
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]

复制

列表函数

list.append(x)

在list末尾添加一个列表元素,元素可以是数字,字符串,列表等常量,也可以是变量--可迭代对象,等同a[len(a):] = [x]

添加常量

>>> list = [1, 3, 5, 7]
>>> list.append(9)
>>> list
[1, 3, 5, 7, 9]

>>> list.append('string')
>>> list
[1, 3, 5, 7, 9, 'string']

>>> cubes = [1, 8, 27, 64, 125]
>>> cubes.append(216) # 6的立方
>>> cubes.append(7 ** 3) # 7的立方
>>> cubes.append('str')
>>> cubes.append([2, 4, 6]) #添加一个list作为原list中的item
>>> cubes
[1, 8, 27, 64, 125, 216, 343, 'str', [2, 4, 6]]

复制

添加变量

>>> x = 3
>>> list.append(x)
>>> list
[1, 3, 5, 7, 9, 'string', 3]

复制

list.extend(L)

把另一个指定list L 中的所有元素添加到原有list末尾来扩展list,等同于list[len(list):] = L

>>> list = []
>>> L = [1, 2, 3]
>>> list.extend(L)
>>> list
[1, 2, 3]
>>> list[len(list):] = L
>>> list
[1, 2, 3, 1, 2, 3]

复制

注意:L也可以不是列表,可以是元组,字符串等序列,如下

>>> test = ("shou", "ke")
>>> test_list = []
>>> test_list.extend(test)
>>> test_list
['shou', 'ke']

>>> test = "shouke"
>>> test_list = []
>>> test_list.extend(test)
>>> test_list
['s', 'h', 'o', 'u', 'k', 'e']
>>> test_list.extend("shouke")
>>> test_list
['s', 'h', 'o', 'u', 'k', 'e', 's', 'h', 'o', 'u', 'k', 'e']

复制

list.insert(i, x)

在指定位置插入一个元素,参数i为list中元素索引,插入位置在该元素之前,所以头部插入为list.insert(0, x),最末尾插入则为list.insert(len(list), x) 等同list.append(x)

>>> list
[1, 2, 3, 1, 2, 3]
>>>list.insert(0, "fisrt")
>>> list
['fisrt', 1, 2, 3, 1, 2, 3]
>>> list.insert(len(list), "last")
>>> list
['fisrt', 1, 2, 3, 1, 2, 3, 'last']


复制

list.remove(x)

移除list中第一个元素值为x的元素,如果元素不存在则返回错误。注意,x 不是索引

>>> list = ['fisrt', 1, 2, 3, 1, 2, 3, 'last']
>>> list.remove(2)
>>> list
['fisrt', 1, 3, 1, 2, 3, 'last']

复制

list.pop([index])

移除list中指定索引位置的元素并返回它。如果未指定索引,list.pop()移除并返回list中最后一个。

>>> list = ['fisrt', 1, 3, 1, 2, 3, 'last']
>>> list.pop()
'last'
>>> list
['fisrt', 1, 3, 1, 2, 3]
>>> list.pop(1)
1
>>> list
['fisrt', 3, 1, 2, 3]
>>> list.pop(0)
'fisrt'

复制

list.clear()

从list中移除所有元素。等同del list[:]

>>> list = [3, 1, 2, 3]
>>> list.clear()
>>> list
[]
>>> list = [3, 1, 2, 3]
>>> del list[:]
>>> list
[]

复制

注:2.7似乎不支持clear()

list.index(x)

返回list中元素值为x的元素的索引,如果元素不存在则返回错误

>>> list = [3, 1, 2, 3]
>>> list.index(3)
0
>>> list.index(1)
1

复制

list.count(x)

返回元素值为x的元素在list中出现的次数

>>> list = [3, 1, 2, 3]
>>> list.count(2)
1
>>> list.count(3)
2
>>> list.count('string')
0

复制

list.sort(*, key=None, reverse=None)

参数说明:

key: 仅携带一个参数的函数,函数的参数用于接收list中每项元素,sort函数会根据key指定的函数的返回值对list中的元素进行排序。

可以理解为,如果key不为None,针对list中的每个元素,以该元素为参数去调用key指定的函数,这样最后会得到多个函数返回值,然后对这些返回值进行排序,每个返回值都关联着对应的元素,所以返回值的排序就是元素的排序。

如果key为None,则直接排序元素值

reverse:False 升序排序(默认),True 降序排序

对list中的元素进行升序排序

>>> list = [5, 2, 9, 10,44]
>>> list.sort()
>>> list
[2, 5, 9, 10, 44]

复制

类似的函数sorted

>>> list = [5, 2, 9, 10, 44]
>>> sorted(list)
[2, 5, 9, 10, 44]
>>> list
[5, 2, 9, 10, 44]

复制

对list中的元素进行降序排序

>>> list.sort(reverse=True)
>>> list
[44, 10, 8, 5, 2]

复制

list元素由元组组成,根据元素项即元组中的第一个值进行排序

>>> list = [(2, 'two'), (4, 'four'), (3, 'three'),  (1, 'one')]
>>> def fn(arg):
print(arg)
return arg[0]

>>> list.sort(key=fn)
(2, 'two')
(4, 'four')
(3, 'three')
(1, 'one')
>>> list
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

复制

等效做法:

>>> list = [(2, 'two'), (4, 'four'), (3, 'three'),  (1, 'one')]
>>> list.sort(key=lambda pair:pair[0])
>>> list
[(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]

复制

list.reverse()

翻转列表中的元素

1)列表元素个数为奇数时,以中间元素为中点,对换两边的元素

>>> list = [44, 10, 9, 5, 2]
>>> list.reverse()
>>> list
[2, 5, 9, 10, 44]

复制

2)列表元素个数为偶数时,以中间两个元素为中点,对换两边元素

>>> list = [44, 10, 9, 5, 6, 2]
>>> list.reverse()
>>> list
[2, 6, 5, 9, 10, 44]

复制

list.copy()

返回list的浅拷贝,等同list[:]

>>> list = [4, 2, 5, 9, 10, 44]
>>> list.copy()
[4, 2, 5, 9, 10, 44]
>>> list[:]
[4, 2, 5, 9, 10, 44]

复制

注:2.7 不支持copy函数

list()转换函数

将序列转换为列表

>>> list("ishouke")
['i', ' ', 's', 'h', 'o', 'u', ' ', 'k', 'e']

复制

将字符串转换为列表

>>> list(range(1, 4))
[1, 2, 3]

>>> squares = list(map(lambda x: x**2, range(10)))
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

复制

将数字序列转换为列表

>>> list(range(1, 4))
[1, 2, 3]

>>> squares = list(map(lambda x: x**2, range(10)))
>>> squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

复制

说明:对range(10)中的每个元素做x**2,并将结果元素转换为列表

将元组转换为列表

>>> list(("i", "shouke"))
['i', 'shouke']

复制

获取字典的键并换为列表

>>> list({1:"i", 2:"shouke"})
[1, 2]

复制

也可以这样

>>> dict_var = {1:"i", 2:"shouke"}
>>> list(dict_var.keys())
[1, 2]

复制

结合zip函数,矩阵行列转置

>>> matrix = [[1, 2, 4], [4, 5, 6]]
>>> list(zip(*matrix))
[(1, 4), (2, 5), (4, 6)]

>>> matrix = [[1, 2, 4]]
>>> list(zip(*matrix))
[(1,), (2,), (4,)]

复制

注意:必须是嵌套列表才可以,否则出错,如下

>>> matrix = [1, 2, 4]
>>> list(zip(*matrix))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: zip argument #1 must support iteration

复制

数据类型转换

把字符串类型的列表转为列表

>>> a = '["i", "shou", "ke"]'
>>> b = eval(a)
>>> type(b)
<class 'list'>
>>> b
['i', 'shou', 'ke']

复制

把列表转为字符串类型列表

>>> a = ["i", "shou", "ke"]
>>> b = str(a)
>>> b
"['i', 'shou', 'ke']"

复制

把列表转为字符串

>>> list = ['test1', 'test2']
>>> ','.join(list)
'test1,test2'
>>> ''.join(list)
'test1test2'
>>> list
['test1', 'test2']

复制

注意:如果列表元素包含非字符串,不能通过join方式把列表转为字符串,否则会报错:

>>> ','.join([2, 3])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected str instance, int found

复制

把元组转为列表

>>> list((2, 3, 4))
[2, 3, 4]

复制

列表统计相关

统计列表数据中,每个元素出现的次数

>>> from collections import Counter
>>> list_data = ['lai', 'yu', 'shouke', 'shouke', 'shouke', 'yu']
>>> c = Counter(list_data)
>>> for item in c.items():
... print(item)
...
('lai', 1)
('shouke', 3)
('yu', 2)

>>> c.most_common(2)
[('shouke', 3), ('yu', 2)]
>>> c.most_common(1)
[('shouke', 3)]
>>>

复制


文章转载自授客的知识库,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论