Python中List 是一种内置数据类型,表示元素的集合。列表用途广泛,可以包含不同数据类 型的元素,包括数字、字符串和其他列表。列表的定义是将元素括在方括号 ( [ ] ) 中并用逗号分隔。
下面是列表的基本示例:
my_list = [1, 2, 3, 'four', 5.0]
在这里,my_list包含整数、字符串、浮点数。
创建列表:
# Empty
print([])// It will create a blank list
# 1D Homogeneous
print([1, 2, 3, 4])// It will create a homogeneous 1D integer list
# 2D Heterogeneous
print([1, 2, 3, [4, 5]])//It will create a homogeneous 2D list
# 3D
print([[[1, 2], [3, 4], [5, 6], [7, 8]]])// It will create a homogeneous 3D list
# Heterogeneous_list
print([1, 'two', 3.0, [4, 5], {'key': 'value'}])// A list can contain any other data types including dictionary.
print(list(range(5))) //To create a list using the list() function with the value 5, an iterable can be passed as an argument
O/t-
[]
[1, 2, 3, 4]
[1, 2, 3, [4, 5]]
[[[1, 2], [3, 4], [5, 6], [7, 8]]]
[1, 'two', 3.0, [4, 5], {'key': 'value'}]
[0, 1, 2, 3, 4]
访问列表中的项目:通过索引和切片,可以访问列表中的元素。
- 索引:列表称为从零开始的索引。这意味着第一个元素的索引为 0,第二个元素的索引为 1,依此类推。
#Indexing
List=[1,2,3,4,5,6]
print(List[0])
#output
1
Python 还支持负索引。在本例中,-1 表示最后一个元素,-2 表示倒数第二个元素,依此类推。
List=[1,2,3,4,5,6]
Print(List[-1])
#output
6
2.切片:编程中的切片是指从列表中提取部分或子序列。切片的基本语法是 start:stop:step 。其工作原理如下:
- start :切片中要的第一个元素的索引(包括)。
- stop :切片中不需要的第一个元素的索引(独占)。
- step :元素之间的步长。
# List Slicing
friend = ["harry","tom","rani","raja","ram","sam"]
print(friend[:3])// First three items of the list
print(friend[-3:])// All the items of the list except the except the first three items
#Output
['harry', 'tom', 'rani']
['raja', 'ram', 'sam']
#Slicing examples
l=[1, 7, 9, 11, 15, 0]
print(l[1:7])
print(l[1:7:1])
print(l[1:7:2])
print(l[-1:-5:-1]) #negative slicing. To do reverse printing
print(l[-1:-5:-2]) #Reverse printing with step size of 2
print(l[-5:-1:1]) #printing using neative indexing
print(l[-5:-1:2])
#Output
[7, 9, 11, 15, 0]
[7, 9, 11, 15, 0]
[7, 11, 0]
[0, 15, 11, 9]
[0, 11]
[7, 9, 11, 15]
[7, 11]
If start is omitted, it defaults to the beginning of the sequence.
If stop is omitted, it defaults to the end of the sequence.
If step is omitted, it defaults to 1.
l=[1, 7, 9, 11, 15, 10]
print(l[:7]) # start is omitted
print(l[1::1]) #end is omitted
print(l[1:7]) #step is omitted
#O/t- [1, 7, 9, 11, 15, 10]
[7, 9, 11, 15, 10]
[7, 9, 11, 15, 10]
3. 循环:您可以使用循环来遍历列表的元素。
# Iterating over each element in the list using a for loopL= [11,2,3,4,5]
for element in L:
print(element)# Output:
1
2
3
4
5
将项目添加到列表:
在 Python 中,和 append() extend() 方法都与列表一起使用以添加元素,但它们具有不同的行为:
- append() 方法:
- 该 append() 方法用于将单个元素添加到列表的末尾。
- 它需要一个参数,即要添加的元素。
- 它修改了原来的列表。
my_list = [1, 2, 3]
my_list.append(4) # Result: [1, 2, 3, 4]
my_list=[1,2,3]
my_list.append([4,5]) # Result: [1, 2, 3, [4,5]]
2. extend() 方法:
- 该 extend() 方法用于将可迭代对象的元素(如列表、元组或字符串)追加到列表的末尾。
- 它需要一个参数,该参数是要添加的可迭代包含元素。
- 它修改了原来的列表
my_list = [1, 2, 3] my_list.extend([4, 5])
# Result: [1, 2, 3, 4, 5]
需要注意的是,它 extend() 采用可迭代对象作为参数,而 append() 采用单个元素。
3. Python 中 insert() 的方法用于在列表中的指定索引处插入元素。
L=[1,2,3,4,5]
L.insert(1,9)
print(L)
#Output
[1,9,2,3,4,5]
编辑列表中的项目:索引或切片可用于编辑列表。
L=[1,2,3,4,5]
# editing with indexing
L[-1]=50
# editing with slicing
L[1:4]=[20,30,40]
print(L)
#Output
[1,2,3,4,50]
[1,20,30,40,5]
删除列表中的项目:
- del (): 语句根据索引删除项。
my_list = [1, 2, 3, 4, 5]
# Delete item at index 2
del my_list[2]
print(my_list)
#Output
my_list =[1,2,4,5]
2. remove() — 根据值删除项目。
my_list = [1, 2, 3, 4, 5]
# Remove item with value 3
my_list.remove(3)
print(my_list)
#Output
my_list=[1,2,4,5]
3. Pop():用于从列表中的特定索引中删除和返回项目。如果您不向 pop() 提供索引,默认情况下它将删除并返回最后一项。
4. Clear():用于从列表中删除所有元素。它修改原始列表,使其为空。
my_list = [1, 2, 3, 4, 5]
# Clear all elements from the list
my_list.clear()
print("Updated list:", my_list)
列表上的操作:
算术:
1. + 运算符:连接两个或多个列表。
L1 = [1, 2, 3]
L2 = [4, 5, 6]
concatenated_list = L1 + L2
print(concatenated_list)
# Output: [1, 2, 3, 4, 5, 6]
2. * operator:重复列表。
L = [1, 2, 3]
repeated_list = L* 3
print(repeated_list)
# Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]
成员身份:成员身份运算符 ( in 和 not in ) 用于测试值或元素是否是序列的成员
L = [1, 2, 3, 4, 5]
# Membership test
print(3 in L)
# Output: True
print(6 in L)
# Output: False
# Negation of membership test
print(3 not in L)
# Output: False
print(6 not in L)
# Output: True
列表函数:可以在一个列表上执行不同的函数:
- Min/Max/Sorted/len 函数可以应用于列表函数。
len/min/max/sorted
L = [3, 1, 4, 1, 5, 9, 2]
length = len(L)
minimum_value = min(L)
maximum_value = max(L)
sorted_list = sorted(L)
print("Minimum:", minimum_value)
print("Maximum:", maximum_value)
# Output:
# Length: 7
# Minimum: 1
# Maximum: 9
# Sorted List: [1, 1, 2, 3, 4, 5, 9]
2. Count(): 用于计算特定元素在列表中的出现次数
L = [1, 2, 3, 2, 4, 1, 5, 2]
count_of_2 = L.count(2)
print(count_of_2)
# Output: 3
3. index() 用于查找列表中首次出现的指定值的索引。
L = [1, 2, 3, 2, 4, 1, 5, 2]
index_of_2 = L.index(2)
print(index_of_2)
# Output: 1
4. reverse() 方法应用于列表,并就地修改列表,反转其元素的顺序。
L = [1, 2, 3, 4, 5]
L.reverse()
print(L)
# Output: [5, 4, 3, 2, 1]
5. sort() 是一种直接处理列表并就地对它们进行排序的方法,而 sorted() 是一个接受可迭代对象、创建新的排序列表并保持原始可迭代对象不变的函数。
#sort vs sorted
L=[9,1,2,3,8,4,5]
print(L)
print(sorted(L))
print(L)
L.sort()
print(L)
#Output
[9,1,2,3,8,4,5]
[1,2,3,4,5,8,9]
[9,1,2,3,8,4,5]
[1,2,3,4,5,8,9]
6. copy() 函数用于创建列表的浅拷贝,这意味着它将引用复制到原始列表中的对象。
列表推导:
优点:使代码更简洁、更易读,有时甚至更有效率。
列表推导式的基本语法:
new_list = [expression for item in iterable if condition]
以下是组件的细分:
- expression :要计算并包含在新列表中的表达式。
- item :表示可迭代对象中每个元素的变量。
- iterable :正在处理的现有可迭代对象(例如,列表、元组、字符串)。
- condition :筛选可迭代对象中的哪些项包含在新列表中的条件。
#Scalar multiplication on a vector
v=[2,3,4]
s=-3
[s*i for i in v]
#Output
[-6,-9,-12]
总之,列表具有许多重要性:
- 有序序列:列表保持元素的顺序,这意味着保留添加元素的顺序。
2. 可变:Python 中的列表是可变的,这意味着可以通过添加、删除或修改元素来修改其内容。
3. 索引和切片:列表支持索引,允许按位置访问单个元素。切片允许您提取数据,从而轻松处理部分数据。
4.异构:列表可以包含不同数据类型的元素。这种多功能性在处理复杂的数据结构时非常有用。
5. 动态内存分配:列表自动管理内存。添加或删除元素时,列表会动态调整其大小,从而有效地满足各种数据存储需求。
虽然在编程中使用列表具有许多优点,但有一些小缺点需要牢记:
Python 列表具有动态类型开销、内存开销,并且由于其调整大小机制,对插入和删除等操作表现出线性时间复杂性。列表的可变性虽然通常是有利的,但如果处理不当,可能会导致意想不到的副作用。修改代码某一部分中的列表可能会影响其他部分,从而可能导致意外行为。