亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python 列表

Python 列表

在本教程中,我们将通过示例了解有关 Python 列表的所有内容:创建列表、更改列表元素、删除元素以及其他列表操作。

视频:Python 列表和元组

Python 列表是最通用的数据类型之一,它允许我们一次处理多个元素。例如,

# a list of programming languages
['Python', 'C++', 'JavaScript']

创建 Python 列表

在 Python 中,通过将元素放在方括号 [] 中来创建列表 , 用逗号分隔。

# list of integers
my_list = [1, 2, 3]

一个列表可以有任意数量的项目,它们可以是不同的类型(整数、浮点数、字符串等)。

# empty list
my_list = []

# list with mixed data types
my_list = [1, "Hello", 3.4]

一个列表也可以有另一个列表作为项目。这称为嵌套列表。

# nested list
my_list = ["mouse", [8, 4, 6], ['a']]

访问列表元素

我们可以通过多种方式访问​​列表的元素。

列出索引

我们可以使用索引运算符[] 访问列表中的项目。在 Python 中,索引从 0 开始。因此,一个包含 5 个元素的列表将具有从 0 到 4 的索引。

尝试访问除这些以外的索引将引发 IndexError .索引必须是整数。我们不能使用 float 或其他类型,这将导致 TypeError .

使用嵌套索引访问嵌套列表。

my_list = ['p', 'r', 'o', 'b', 'e']

# first item
print(my_list[0])  # p

# third item
print(my_list[2])  # o

# fifth item
print(my_list[4])  # e

# Nested List
n_list = ["Happy", [2, 0, 1, 5]]

# Nested indexing
print(n_list[0][1])

print(n_list[1][3])

# Error! Only integer can be used for indexing
print(my_list[4.0])

输出

p
o
e
a
5
Traceback (most recent call last):
  File "<string>", line 21, in <module>
TypeError: list indices must be integers or slices, not float

负索引

Python 允许对其序列进行负索引。 -1 的索引是指最后一项,-2 是指倒数第二项,依此类推。

# Negative indexing in lists
my_list = ['p','r','o','b','e']

# last item
print(my_list[-1])

# fifth last item
print(my_list[-5])

输出

e
p
<图>

Python 中的列表切片

我们可以使用切片运算符 : 访问列表中的一系列项目 .

# List slicing in Python

my_list = ['p','r','o','g','r','a','m','i','z']

# elements from index 2 to index 4
print(my_list[2:5])

# elements from index 5 to end
print(my_list[5:])

# elements beginning to end
print(my_list[:])

输出

['o', 'g', 'r']
['a', 'm', 'i', 'z']
['p', 'r', 'o', 'g', 'r', 'a', 'm', 'i', 'z']

注意: 当我们对列表进行切片时,开始索引是包含的,而结束索引是排除的。例如,my_list[2: 5] 返回一个包含索引为 2、3 和 4,但不是 5 的元素的列表。


添加/更改列表元素

列表是可变的,这意味着它们的元素可以改变,不像字符串或元组。

我们可以使用赋值运算符= 更改一个项目或一系列项目。

# Correcting mistake values in a list
odd = [2, 4, 6, 8]

# change the 1st item    
odd[0] = 1            

print(odd)

# change 2nd to 4th items
odd[1:4] = [3, 5, 7]  

print(odd)                   

输出

[1, 4, 6, 8]
[1, 3, 5, 7]

我们可以使用 append() 将一项添加到列表中 方法或使用 extend() 添加多个项目 方法。

# Appending and Extending lists in Python
odd = [1, 3, 5]

odd.append(7)

print(odd)

odd.extend([9, 11, 13])

print(odd)

输出

[1, 3, 5, 7]
[1, 3, 5, 7, 9, 11, 13]

我们也可以使用 + 运算符来组合两个列表。这也称为串联。

* 运算符重复一个列表给定的次数。

# Concatenating and repeating lists
odd = [1, 3, 5]

print(odd + [9, 7, 5])

print(["re"] * 3)

输出

[1, 3, 5, 9, 7, 5]
['re', 're', 're']

此外,我们可以使用 insert() 方法在所需位置插入一项 或通过将多个项目挤压到列表的空切片中来插入多个项目。

# Demonstration of list insert() method
odd = [1, 9]
odd.insert(1,3)

print(odd)

odd[2:2] = [5, 7]

print(odd)

输出

[1, 3, 9]
[1, 3, 5, 7, 9]

删除列表元素

我们可以使用 Python del 语句从列表中删除一个或多个项目。它甚至可以完全删除列表。

# Deleting list items
my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# delete one item
del my_list[2]

print(my_list)

# delete multiple items
del my_list[1:5]

print(my_list)

# delete the entire list
del my_list

# Error: List not defined
print(my_list)

输出

['p', 'r', 'b', 'l', 'e', 'm']
['p', 'm']
Traceback (most recent call last):
  File "<string>", line 18, in <module>
NameError: name 'my_list' is not defined

我们可以使用 remove() 删除给定的项目或 pop() 删除给定索引处的项目。

pop() 如果未提供索引,方法将删除并返回最后一项。这有助于我们将列表实现为堆栈(先进后出数据结构)。

而且,如果我们必须清空整个列表,我们可以使用 clear() 方法。

my_list = ['p','r','o','b','l','e','m']
my_list.remove('p')

# Output: ['r', 'o', 'b', 'l', 'e', 'm']
print(my_list)

# Output: 'o'
print(my_list.pop(1))

# Output: ['r', 'b', 'l', 'e', 'm']
print(my_list)

# Output: 'm'
print(my_list.pop())

# Output: ['r', 'b', 'l', 'e']
print(my_list)

my_list.clear()

# Output: []
print(my_list)

输出

['r', 'o', 'b', 'l', 'e', 'm']
o
['r', 'b', 'l', 'e', 'm']
m
['r', 'b', 'l', 'e']
[]

最后,我们还可以通过将空列表分配给元素切片来删除列表中的项目。

>>> my_list = ['p','r','o','b','l','e','m']
>>> my_list[2:3] = []
>>> my_list
['p', 'r', 'b', 'l', 'e', 'm']
>>> my_list[2:5] = []
>>> my_list
['p', 'r', 'm']

Python 列表方法

Python 有许多有用的列表方法,使得使用列表变得非常容易。以下是一些常用的列表方法。

方法 说明
append() 在列表末尾添加一个元素
扩展() 将一个列表的所有元素添加到另一个列表中
插入() 在定义的索引处插入一个项目
删除() 从列表中删除一个项目
pop() 返回并删除给定索引处的元素
clear() 从列表中删除所有项目
索引() 返回第一个匹配项的索引
count() 返回作为参数传递的项目数的计数
排序() 按升序对列表中的项目进行排序
reverse() 颠倒列表中项目的顺序
复制() 返回列表的浅拷贝
# Example on Python list methods

my_list = [3, 8, 1, 6, 8, 8, 4]

# Add 'a' to the end
my_list.append('a')

# Output: [3, 8, 1, 6, 0, 8, 4, 'a']
print(my_list)

# Index of first occurrence of 8
print(my_list.index(8))   # Output: 1

# Count of 8 in the list
print(my_list.count(8))  # Output: 3 

列表理解:创建列表的优雅方式

列表推导式是一种优雅而简洁的方式,可以从 Python 中的现有列表创建新列表。

列表推导式由一个表达式后跟方括号内的 for 语句组成。

这是一个创建列表的示例,每个项目的幂为 2。

pow2 = [2 ** x for x in range(10)]
print(pow2)

输出

[1, 2, 4, 8, 16, 32, 64, 128, 256, 512]

这段代码相当于:

pow2 = []
for x in range(10):
   pow2.append(2 ** x)

列表推导可以选择包含更多 for 或 if 语句。可选的 if 语句可以过滤掉新列表的项目。下面是一些例子。

>>> pow2 = [2 ** x for x in range(10) if x > 5]
>>> pow2
[64, 128, 256, 512]
>>> odd = [x for x in range(20) if x % 2 == 1]
>>> odd
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x+y for x in ['Python ','C '] for y in ['Language','Programming']]
['Python Language', 'Python Programming', 'C Language', 'C Programming']

访问 Python 列表推导了解更多信息。


Python 中的其他列表操作

列出成员资格测试

我们可以使用关键字 in 来测试一个项目是否存在于列表中 .

my_list = ['p', 'r', 'o', 'b', 'l', 'e', 'm']

# Output: True
print('p' in my_list)

# Output: False
print('a' in my_list)

# Output: True
print('c' not in my_list)

输出

True
False
True

遍历列表

使用 for 循环我们可以遍历列表中的每一项。

for fruit in ['apple','banana','mango']:
    print("I like",fruit)

输出

I like apple
I like banana
I like mango

Python

  1. Python 数据类型
  2. Python 运算符
  3. Python pass 语句
  4. Python 函数参数
  5. Python字典
  6. Python 睡眠()
  7. Python 列表理解、追加、排序、长度 [示例]
  8. Python 平均值:如何在 Python 中找到列表的平均值
  9. 带有示例的 Python 列表计数()
  10. Python从列表中删除重复项
  11. 从 Python LIST 中移除元素 [clear, pop, remove, del]
  12. Python 列表 index() 与示例