Python数据类型List列表

本文介绍了Python列表。 我们将向您展示如何创建列表,对列表进行切片和排序,从列表中添加或删除元素,等等。列表是可变的序列,这意味着它们可以在创建后进行更改。 列表是Python中最常用的数据类型之一,通常用于存储相同类型的元素的集合

8 min read
By myfreax
Python数据类型List列表

Python包含许多顺序数据类型,这些数据类型使您能够以有组织的高效方式存储数据集合。 基本序列类型是列表lists,元组tuples和范围range对象。

本文介绍了Python列表。 我们将向您展示如何创建列表,对列表进行切片和排序,从列表中添加或删除元素,等等。

列表是可变的序列,这意味着它们可以在创建后进行更改。 列表是Python中最常用的数据类型之一,通常用于存储相同类型的元素的集合。

创建列表lists

列表通常是通过将元素放在一对用逗号分隔的方括号[]中来创建的。 它们可以具有任意数量的元素,这些元素可以是不同的类型。 这是一个例子:

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())来构造。

访问列表lists元素

列表项可以通过其索引引用。 索引是整数,从0n-1,其中n是项数:

L = ["a", "b", "c", "d"]
      0    1    2    3

在Python中,索引用方括号括起来:

L[index]

例如,要访问列表的第二个元素,您可以使用:

colors = ['orange', 'white', 'green']
'white'

如果您引用的索引不存在,则会引发IndexError异常:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

要访问嵌套列表中的元素,请使用多个索引:

L = [1, 2, ["red", "blue"]]
'blue'

Python还允许您使用负索引访问列表项。 最后一项称为-1,第二项称为-2,依此类推:

L = ["a", "b", "c", "d"]
     -4   -3   -2   -1

例如,要从末尾访问第二个元素,应使用:

colors = ['orange', 'white', 'green']
'white'

列表切片

在Python中,您可以使用以下形式对列表进行切片:

L[start:stop:step]
  • 第一个参数指定开始提取的索引。 使用负索引时,它表示从列表末尾开始的偏移量。 如果省略此参数,则切片从索引0开始。
  • 第二个参数指定终止提取之前的索引; 结果不包含“停止”元素。 使用负索引时,它表示从列表末尾开始的偏移量。 如果省略此参数或大于列表的长度,则切片将到达列表的末尾。
  • 第三个参数是可选的,它指定切片的step。 如果不使用“ 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. 从start开始到最后的元素,对列表进行切片
L[:stop] # slice the list starting from the begging up to but not including the element with index "stop".从0开始到stop停止的位置对列表进行切片,但不包括停止元素
L[start:stop] #  slice the list starting from the element with index "start" up to but not including the element with index "stop". 从start到stop进行切片,但不包括stop停止元素
stop"
L[::step] #  slice the list with a stride of "step"

以下是一个基本示例,该示例说明如何切片从索引为1的元素开始到但不包括索引为4的元素的列表:

fruits = ['Apple', 'Peach', 'Lemon', 'Strawberry', 'Grape']
['Peach', 'Lemon', 'Strawberry']

更新元素值

要更改列表中特定元素的值,请参考其索引号:

L[index] = value

以下示例显示了如何更新列表的最后一个元素的值:

colors = ['orange', 'white', 'green']
['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']
['orange', 'red']

替换块可以具有与列表相比较小,较大或相同数量的元素。 这样就可以扩大或缩小列表。

将元素添加到列表中

列表数据类型有两种方法,可让您将元素添加到列表中append()insert()

append()方法将一个元素添加到列表的末尾。 append()方法的语法如下:

L.append(element)

“element”是要添加到列表中的元素。 它可以是任何数据类型,包括列表。 这是一个例子:

colors = ['orange', 'white', 'green']
colors = ['orange', 'white', 'green']
colors.append('red')
print(colors)
['orange', 'white', 'green', 'red']

insert()方法在列表中的特定位置添加元素,并具有以下语法:

L.insert(index, element)

“index”是要插入元素的位置,“element”是要在列表中添加的元素。 下面的示例演示如何将元素添加到列表的第一个位置:

colors = ['orange', 'white', 'green']
colors = ['orange', 'white', 'green']
colors.insert(0, 'red')
print(colors)
['red', 'orange', 'white', 'green']

extend()方法允许您扩展包含多个元素的列表。 它采用一个参数,并具有以下语法:

L.extend(list)

“list”的元素附加在“ L”的末尾。 这是一个例子:

colors = ['orange', 'white', 'green']
['orange', 'white', 'green', 'blue', 'black']

从列表中删除元素

remove()方法采用一个参数,并从列表中删除值与该参数匹配的第一个元素:

L.remove(element)
colors = ['orange', 'white', 'orange', 'green']
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 = ['orange', 'white', 'green']
colors.pop(1)
print(colors)
'white'
['orange', 'green']

与切片符号结合使用del关键字可以删除多个元素。 例如,要从列表中删除前两个元素,请使用以下命令:

colors = ['orange', 'white', 'orange', 'green']
colors = ['orange', 'white', 'orange', 'green']
del colors[0:2]
print(colors)
['orange', 'green']

要删除所有元素,请使用clear()方法,该方法将清除列表并且不接受任何参数:

colors = ['orange', 'white', 'green']
colors = ['orange', 'white', 'green']
colors.clear()
print(colors)
[]

查找列表的长度

内置len()函数返回对象的元素总数。

要查找列表的长度,请将其作为参数传递给len()函数:

len(L)

以下是示例:

colors = ['orange', 'white', 'green']
colors = ['orange', 'white', 'green']
num = len(colors)
print(num)
3

遍历列表

要遍历列表中的所有元素,请使用for循环:

colors = ['orange', 'white', 'green']
colors = ['orange', 'white', 'green']
for color in colors:
    print(color)
orange
white
green

如果您需要显示索引,则可以使用几种方法。 最常见的方法是组合 range() len()函数或使用内置的 enumerate() 函数。

以下示例显示了如何检索列表中每个元素的索引和值:

colors = ['orange', 'white', 'green']
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']
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

检查元素是否存在

要检查列表中是否存在某项,可以使用innot in运算符:

colors = ['orange', 'white', 'green']
print('orange' in colors)

输出将为TrueFalse

True

以下是使用 if语句的另一个示例:

colors = ['orange', 'white', 'green']
colors = ['orange', 'white', 'green']
if 'blue' not in colors:
    print('no')
else:
    print('yes')

输出将为TrueFalse

no

Python列表方法

列表对象具有以下方法:

  • append(x)-在列表末尾附加元素。
  • clear() -从列表中删除所有元素。
  • copy() -返回列表的浅表副本。
  • count(x) -返回“ x”出现在列表中的次数。
  • extend(iterable) -将“可迭代”追加到列表末尾。
  • index(x) -返回值为“ x”的元素首次出现的位置。
  • insert(i, x) -在给定位置添加元素。
  • pop(i) -从给定位置移除元素。
  • remove() -删除具有给定值的元素。
  • reverse() -反转列表的元素
  • sort() -对列表的元素进行排序。

结论

在本文中,我们讨论了如何在Python中创建和使用列表。

列表数据类型包括许多有用的方法。

如果您有任何问题或反馈,请随时发表评论

Related Articles