Python列表
Python包含许多顺序数据类型,这些数据类型使您能够以有组织的高效方式存储数据集合。 基本序列类型是列表,元组和范围对象。
本文介绍了Python列表。 我们将向您展示如何创建列表,对列表进行切片和排序,如何从列表中添加或删除元素,等等。
列表是可变的序列,这意味着它们可以在创建后进行更改。 列表是Python中最常用的数据类型之一,通常用于存储相同类型的项目的集合。
创建列表
列表通常是通过将项目放在一对方括号内来创建的 []
, 被逗号隔开。 它们可以具有任意数量的项目,这些项目可以是不同的类型。 这是一个例子:
L = ['orange', 'white', 'green']
方括号之间没有元素的方括号表示一个空列表:
L = []
尽管Python列表通常是同质的,但是您可以使用混合数据类型的项目:
L = [1, 'white', 6.5]
您还可以声明嵌套列表,其中一个或多个项目也是列表:
L = [1, 2, ['red', 'blue']]
多个元素可以具有相同的值:
L = [1, 2, 3, 2, 2, 1]
列表也可以使用列表理解来构建, list()
构造函数以及其他内置函数,例如 sorted()
。
访问列表元素
列表项可以通过其索引引用。 索引是整数,从 0
至 n-1
哪里 n
是项目数:
L = ["a", "b", "c", "d"]
0 1 2 3
在Python中,索引用方括号括起来:
L[index]
例如,要访问列表的第二个元素,您可以使用:
colors = ['orange', 'white', 'green']
colors[1]
'white'
如果您引用的索引不存在, IndexError
引发异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
要访问嵌套列表中的项目,请使用多个索引:
L = [1, 2, ["red", "blue"]]
L[2][1]
'blue'
Python还允许您使用负索引访问列表项。 最后一项称为 -1
,倒数第二个项目为 -2
等等:
L = ["a", "b", "c", "d"]
-4 -3 -2 -1
例如,要从头访问第二个元素,可以使用:
colors = ['orange', 'white', 'green']
colors[-2]
'white'
切片列表
在Python中,您可以使用以下形式对列表进行切片:
L[start:stop:step]
- 第一个参数指定开始提取的索引。 使用负索引时,它表示从列表末尾开始的偏移量。 如果省略此参数,则切片从索引0开始。
- 第二个参数指定结束提取之前的索引; 结果不包含“停止”元素。 使用负索引时,它表示从列表末尾开始的偏移量。 如果省略此参数或大于列表的长度,则切片将到达列表的末尾。
- 第三个参数是可选的,它指定切片的步骤。 如果不使用“ step”参数,则默认为1。使用负值时,切片将采用相反的顺序获取元素。
对列表进行切片的结果是包含提取的元素的新列表,并且原始列表未修改。
以下所有都是合法的Python语法:
L[:] # copy whole list
L[start:] # slice the list starting from the element with index "start" to the end of the list.
L[:stop] # slice the list starting from the begging up to but not including the element with index "stop".
L[start:stop] # slice the list starting from the element with index "start" up to but not including the element with index "stop".
stop"
L[::step] # slice the list with a stride of "step"
下面是一个基本示例,该示例如何切片从索引为1的元素开始到但不包括索引为4的元素的列表:
fruits = ['Apple', 'Peach', 'Lemon', 'Strawberry', 'Grape']
fruits[1:4]
['Peach', 'Lemon', 'Strawberry']
更新元素值
要更改列表中特定项目的值,请参考其索引号:
L[index] = value
这是显示如何更新列表的最后一个元素的值的示例:
colors = ['orange', 'white', 'green']
colors[-1] = "blue"
print(colors)
['orange', 'white', 'blue']
如果存在具有给定索引的元素,则更新值。 否则一个 IndexError
引发异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
您还可以使用新值更新列表的一部分:
colors = ['orange', 'white', 'green']
colors[1:3] = ['red']
print(colors)
['orange', 'red']
替换块可以具有与列表相比较小,较大或相同数量的项目。 这使您可以扩展或缩小列表。
将元素添加到列表中
list数据类型有两种方法,可让您将元素添加到列表中, append()
和 insert()
。
的 append()
方法将项目添加到列表的末尾。 的语法 append()
方法如下:
L.append(element)
“元素”是要添加到列表中的项目。 它可以是任何数据类型,包括列表。 这是一个例子:
colors = ['orange', 'white', 'green']
colors.append('red')
print(colors)
['orange', 'white', 'green', 'red']
的 insert()
方法广告列表中特定位置的项目,语法如下:
L.insert(index, element)
“索引”是要插入元素的位置,“元素”是要添加到列表中的项目。 以下示例显示如何在第一个位置的列表中添加元素:
colors = ['orange', 'white', 'green']
colors.insert(0, 'red')
print(colors)
['red', 'orange', 'white', 'green']
的 extend()
方法允许您扩展包含多个元素的列表。 它只有一个参数,语法如下:
L.extend(list)
“列表”的元素附加到“ L”的末尾。 这是一个例子:
colors = ['orange', 'white', 'green']
colors.extend(['blue', 'black'])
print(colors)
['orange', 'white', 'green', 'blue', 'black']
从列表中删除元素
的 remove()
方法采用一个参数,并从列表中删除值与该参数匹配的第一个元素:
L.remove(element)
colors = ['orange', 'white', 'orange', 'green']
colors.remove('orange')
print(colors)
['white', 'orange', 'green']
如果具有给定值的元素不存在,则 ValueError
引发异常:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: list.remove(x): x not in list
的 pop()
方法采用一个参数,并从列表中删除索引与该参数匹配的元素:
L.pop(element)
参数是可选的,默认为“ -1”,这是列表的最后一项。 该方法的返回值是删除的项目。 这是一个例子:
colors = ['orange', 'white', 'green']
colors.pop(1)
print(colors)
'white'
['orange', 'green']
的 del
关键字与切片符号结合使用,可以删除多个项目。 例如,要从列表中删除前两个项目,可以使用以下命令:
colors = ['orange', 'white', 'orange', 'green']
del colors[0:2]
print(colors)
['orange', 'green']
要删除所有项目,请使用 clear()
方法,该方法清除列表并且不接受任何参数:
colors = ['orange', 'white', 'green']
colors.clear()
print(colors)
[]
查找列表的长度
内建 len()
函数返回一个对象的项目总数。
要查找列表的长度,请将其作为参数传递给 len()
功能:
len(L)
这是一个例子:
colors = ['orange', 'white', 'green']
num = len(colors)
print(num)
3
遍历列表
要遍历列表中的所有项目,请使用 for
循环:
colors = ['orange', 'white', 'green']
for color in colors:
print(color)
orange
white
green
如果需要索引,则可以使用几种方法。 最常见的方法是将 range()
和 len()
功能或使用内置 enumerate()
功能。
下面的示例显示如何检索列表中每个项目的索引和值:
colors = ['orange', 'white', 'green']
for i in range(len(colors)):
print("Index {} : Value {}".format(i, colors[i]))
Index 0 : Value orange
Index 1 : Value white
Index 2 : Value green
而不是使用 range(len(...))
您可以使用的模式 enumerate()
函数以更Python化的方式遍历列表:
colors = ['orange', 'white', 'green']
for index, value in enumerate(colors):
print("Index {} : Value {}".format(index, value))
Index 0 : Value orange
Index 1 : Value white
Index 2 : Value green
检查元素是否存在
要检查列表中是否存在某项,您可以使用 in
和 not in
运营商:
colors = ['orange', 'white', 'green']
print('orange' in colors)
输出将是 True
要么 False
:
True
这是使用 if
声明:
colors = ['orange', 'white', 'green']
if 'blue' not in colors:
print('no')
else:
print('yes')
输出将是 True
要么 False
:
no
Python清单方法
列表对象接受以下方法:
append(x)
-在列表末尾附加项目。clear()
-从列表中删除所有项目。copy()
-返回列表的浅表副本。count(x)
-返回“ x”出现在列表中的次数。extend(iterable)
-将“可迭代”追加到列表的末尾。index(x)
-返回值为“ x”的元素首次出现的位置。insert(i, x)
-在给定位置添加项目。pop(i)
-从给定位置删除项目。remove()
-删除具有给定值的项目。reverse()
-反转列表的元素。sort()
-对列表中的项目进行排序。
结论#
在本文中,我们讨论了如何在Python中创建和使用列表。
列表数据类型包括许多有用的方法。
如果您有任何疑问或反馈,请随时发表评论
蟒蛇