python 列表与元组
Area: 编程
Python列表与元组
在python中,变量不是一个盒子,当赋值运算发生时,python并不是将数据放到变量里边去,而是将变量与数据进行挂钩,这个行为我们称之为引用。将一个变量赋值给另一个变量其实就是将一个变量的引用传递给另一个变量。
在Python中,列表是一种有序且可变的数据结构,是Python中最常用的数据结构之一。它们用于存储一组相关的数据项,这些数据项可以是不同的数据类型,例如字符串,整数甚至是其他列表。
创建列表
要创建Python中的列表,您可以使用方括号[]
将一系列值括起来,用逗号分隔。例如:
fruits = ['apple', 'banana', 'orange']
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, 'apple', True, 3.14]
#空列表
s=[]
您可以通过使用它们的索引值来访问列表中的单个项。索引从0开始,代表列表中的第一项,1表示第二项,以此类推。例如,要访问fruits
列表中的第一项,您可以使用fruits[0]
。
访问列表项
您可以通过使用它们的索引值来访问列表中的单个项。索引从0开始,代表列表中的第一项,1表示第二项,以此类推。例如,要访问fruits
列表中的第一项,您可以使用fruits[0]
。
修改列表项
列表是可变的,这意味着您可以通过将新值分配给特定索引位置来修改其内容。例如:
列表变量名的赋值只不过是引用的拷贝,如果你修改了列表中的元素,那么会影响到另外一个指向它的引用:
>>> s = [1, 2, 3, 4, 5]
>>> t = s
>>> s[2] = 1
>>> print(t)
export:[1,2,1,4,5]
fruits = ['apple', 'banana', 'orange']
fruits[1] = 'grape'
print(fruits) # 输出:['apple','grape','orange']
>>> s = [1, 2, 3, 4, 5]
>>> s[:] = "FishC"
>>> print(s)
输出:['F', 'i', 's', 'h', 'C']
同样先删除再替换,不过这回我们**删除的是整个列表**,然后再将赋值号(=)右边的***可迭代对象(字符串)的每个元素插入到列表里面***。高阶操作,记好笔记!
对数字列表执行简单的统计计算
有几个专门用于处理数字列表的Python函数。例如,你可以轻松地找出数字列表的最大值、
最小值和总和:
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
0
max(digits)
9
sum(digits)
45
列表方法
Python提供了几个内置方法来操作列表,例如Python提供了几个内置方法来操作列表,例如:
append()
:添加一个元素到列表的末尾extend()
:参数为一个可迭代对象,[”fishc”]为字符串整体只有一个元素,而”fishc”则是多个元素insert()
:在指定的索引位置插入元素remove()
:从列表中删除指定的元素pop()
:从列表中弹出指定索引位置的元素sort()
:对列表进行排序,sort(reverse = True)
:排序后翻转reverse()
:翻转列表count()
:查找计数index()
:索引copy()
:拷贝nums.copy()
等效于nums[:]
,调用列表的 copy()
方法实现的是浅拷贝,浅拷贝,只能拷贝第一层数据,其余仅拷贝其引用
x = [[1, 2, 3], [4, 5, 6]]
y = x.copy()
y.append(7)
y[1].append(8)
列表 x 变成 [[1, 2, 3], [4, 5, 6, 8]],列表 y 变成 [[1, 2, 3], [4, 5, 6, 8], 7],
y.append(7) 是往列表 y 添加一个新元素 7,这一步操作对列表 x 并不会产生任何影响;
但是,y[1].append(8) 是往列表 y 的内嵌列表添加一个新元素,由于是浅拷贝,所以两个内嵌的列表是 x 和 y 共享的,该操作也会对列表 x 产生影响
>>> s = [1]
>>> s.append(s)
[1, [...]]
Python列表切片
Python的列表切片允许您从列表中选择一部分项,并在新列表中返回它们。可以使用冒号运算符来执行切片操作。
切片操作的一般语法如下:
new_list = old_list[start:end:step]
s[len(s)] = ["hello"]#将'hello'加入列表末尾
#执行步骤1:将赋值号左侧指定位置的内容清空
#执行步骤2:将赋值号右侧可迭代对象的内容插入到左侧列表被清空的位置
例如:
>>> s = [1, 2, 3, 4, 5]
>>> s[len(s)-2:] = [2, 1]
输出:[1, 2, 3, 2, 1]
start
:切片的起始索引。如果未指定,则默认为0。end
:切片的结束索引。如果未指定,则默认为列表的长度。结束位置的元素是不包含的。step
:在切片时要跳过的元素数。如果未指定,则默认为1。
下面是一些示例:
fruits = ['apple', 'banana', 'orange', 'grape', 'kiwi']
# 返回第二项到第四项,不包括第四项
print(fruits[1:3]) # 输出:['banana', 'orange']
# 返回最后一项
print(fruits[-1]) # 输出:'kiwi'
# 返回倒数第二项到倒数第一项
print(fruits[-2:]) # 输出:['grape', 'kiwi']
# 返回所有奇数索引项
print(fruits[1::2]) # 输出:['banana', 'grape']
# 返回反向列表
print(fruits[::-1]) # 输出:['kiwi', 'grape', 'orange', 'banana', 'apple']
注意,切片操作返回一个新列表,而不是修改原始列表。此外,切片操作的结束索引是不包括在切片中的,因此第一个示例中的第四项('grape')不包括在内。
总之,Python的列表切片功能非常强大,可以让您轻松地选择和操作列表中的子集。
列表的浅拷贝与深拷贝
浅拷贝
调用列表的copy方法
x = [1, 2, 3]
y = x.copy()
x[1] = 1
print(x) # 输出:[1, 1, 3]
print(y) # 输出:[1, 2, 3]
[copy方法拷贝的是整个列表对象,而不仅仅是变量的引用]
利用切片的方法也可以实现拷贝的效果
>>> x = [1, 2, 3]
>>> y = x[:]
>>> x[1] = 1
>>> x
[1, 1, 3]
>>> y
[1, 2, 3]
浅拷贝方法无法处理嵌套列表
>>> x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> y = x.copy()
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
[浅拷贝只是拷贝了外层的对象,如果包含嵌套对象的话,只是其引用]
- copy模板
有两个函数,copy实现的是浅拷贝,deepcopy实现的是深拷贝。
- copy
import copy
x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
y = copy.copy(x)
x[1][1] = 0
print(x) # [[1, 2, 3], [4, 0, 6], [7, 8, 9]]
print(y) # [[1, 2, 3], [4, 0, 6], [7, 8, 9]]
- deepcopy
>>>import copy
>>>x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> y = copy.deepcopy(x)
>>> x[1][1] = 0
>>> x
[[1, 2, 3], [4, 0, 6], [7, 8, 9]]
>>> y
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[deepcopy将原对象拷贝的同时,也将对象中所有引用的子对象一并进行了拷贝
如果存在多层嵌套的话,深拷贝也会360度无死角地拷贝每一层嵌套里面的数据。]
默认使用的是浅拷贝,因为效率,深拷贝需要更多空间,浅拷贝只要复制地址就行了
copy()
(shallow copy):
Thecopy()
method creates a new object, but does not create new copies of nested objects. Instead, it creates new references to the nested objects within the original object. This is called a shallow copy. If the original object contains mutable nested objects (e.g., lists or dictionaries), changes made to the nested objects in the copied object will also affect the original object.
Here's an example to illustrate the behavior of copy()
:
import copy
original_list = [1, 2, [3, 4]]
shallow_copied_list = copy.copy(original_list)
shallow_copied_list[2][0] = 99
print(original_list) # Output: [1, 2, [99, 4]]
As you can see, modifying the nested list in shallow_copied_list
also affected the original_list
.
copy.deepcopy()
(deep copy):
Thedeepcopy()
method creates a new object and also recursively creates new copies of all nested objects within the original object. This is called a deep copy. Since deep copying creates entirely independent copies of nested objects, changes made to the nested objects in the copied object will not affect the original object.
Here's an example to illustrate the behavior of deepcopy()
:
import copy
original_list = [1, 2, [3, 4]]
deep_copied_list = copy.deepcopy(original_list)
deep_copied_list[2][0] = 99
print(original_list) # Output: [1, 2, [3, 4]]
In this case, modifying the nested list in deep_copied_list
did not affect the original_list
.
In summary, the difference between copy()
and copy.deepcopy()
is that copy()
creates a shallow copy with references to the original nested objects, while deepcopy()
creates a deep copy with entirely independent copies of all nested objects. The choice between the two depends on whether you want to create an entirely independent copy or a copy that shares references to the original object's nested objects.
列表推导式
列表推导式是Python中创建列表的简洁方法。它们允许您通过将函数或表达式应用于现有列表中的每个项来创建新列表。例如:
List comprehensions consist of an expression followed by a for
clause, and optionally one or more if
clauses. The resulting list comprehension consists of the output of the expression for each item in the iterable that meets the conditions specified in the if
clauses.
[expression for item in iterable if condition]
Example 1
: Create a list of squares for numbers from 0 to 9:
squares = [x**2 for x in range(10)]
print(squares)
>>> diag = [i * matrix[i][i] for i in range(len(matrix))]
>>> diag
[0, 5, 18]
Output:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Example 2
: Create a list of even numbers from 0 to 20:
even_numbers = [x for x in range(21) if x % 2 == 0]
print(even_numbers)
Output:
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Example 3
: Create a list of uppercase versions of the words in a given list, but only if the word's length is greater than 3:
words = ['apple', 'banana', 'cherry', 'date', 'fig', 'grape']
uppercase_words = [word.upper() for word in words if len(word) > 3]
print(uppercase_words)
Output:
['APPLE', 'BANANA', 'CHERRY', 'GRAPE']
List comprehensions are a powerful feature in Python, allowing you to create new lists quickly and concisely. However, it's important to note that if a list comprehension becomes too complex or hard to read, it might be better to use a regular loop to create the list for the sake of code readability.
To downscale a two-dimensional matrix into a one-dimensional matrix (also called flattening the matrix) in Python, you can use a nested list comprehension or the itertools.chain
function.
Here are two methods to achieve this:
Method 1: Using list comprehension
pythonCopy code
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
flat_matrix = [elem for row in matrix for elem in row] #注意迭代的运用
print(flat_matrix)
Output:
csharpCopy code
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Method 2: Using itertools.chain
pythonCopy code
import itertools
matrix = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
flat_matrix = list(itertools.chain.from_iterable(matrix))
print(flat_matrix)
Output:
csharpCopy code
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Both methods will result in the same flattened one-dimensional matrix. The first method uses a nested list comprehension, while the second method uses the chain.from_iterable()
function from the itertools
module. Choose the method that best suits your needs and coding style.
列表的赋值
- x:
x = [[0]*3]*3
>>> x[0][0] = 1
>>> print(x)
[[1, 0, 0], [1, 0, 0], [1, 0, 0]]
x
is a 3x3 list (nested list) containing zeros. However, this method of initializing nested lists creates shallow copies. It means that all three inner lists are actually references to the same list. If you modify one inner list, the changes will be reflected in all of them.
- y:
y = [0] * 3
for i in range(3):
y[i] = [0] * 3
>>> y[0][0] = 1
>>> print(y)
[[1, 0, 0], [0, 0, 0], [0, 0, 0]]
y
is also a 3x3 list containing zeros, just like x
. However, unlike x
, y
is created using a loop that ensures each inner list is a separate instance. Modifying one inner list will not affect the others.
- z:
z = [0] * 3
for i in range(3):
z[i] = [0] * 3
for j in range(3):
z[i][j] = [0] * 2
>>> z[0][0][0] = 1
>>> print(z)
[[[1, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]]
z
is a 3x3x2 nested list (3D list) containing zeros. Each element of the outer list is a separate 3x2 nested list, and the inner lists are separate instances as well. Modifying one inner list will not affect the others.
To summarize:
x
is a shallow copy 3x3 list containing zeros, which means modifying one inner list will affect all the inner lists.y
is a deep copy 3x3 list containing zeros, where each inner list is a separate instance.z
is a 3x3x2 3D nested list containing zeros, with each inner list being a separate instance.
Tuples(元组) are useful in various scenarios where you need an immutable, ordered collection of elements. Some common use cases for tuples include:
Tuples(元组)
-
Multiple value assignment: Tuples can be used to assign multiple values to multiple variables in a single statement, which is also known as tuple unpacking.
pythonCopy code a, b, c = (1, 2, 3) print(a) # Output: 1 print(b) # Output: 2 print(c) # Output: 3
-
Returning multiple values from a function: Functions can return multiple values as a tuple.
pythonCopy code def get_name_age(): return "Alice", 30 name, age = get_name_age() print(name) # Output: Alice print(age) # Output: 30
-
Immutable data: Tuples can be used when you need to ensure that the data remains constant and cannot be modified. This is useful when you want to create a fixed set of elements that should not be altered during the execution of your program.
pythonCopy code weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
-
Dictionary keys: Tuples can be used as keys in dictionaries, unlike lists, because they are immutable and hashable.
pythonCopy code employee_data = {("John", "Doe"): {"age": 30, "position": "Software Engineer"}, ("Jane", "Smith"): {"age": 28, "position": "Data Scientist"}}
-
Efficiency: Since tuples are more memory-efficient than lists, they can be used in performance-critical parts of your code where a small difference in memory usage matters.
These are just a few examples of how tuples can be used in Python. Generally, you would use tuples when you have a fixed number of ordered elements that should not be modified.
Both tuples and lists are data structures in Python that can be used to store a collection of items. However, there are some key differences between them:
- Mutability: Lists are mutable, which means you can change their content (add, remove, or modify items) after they are created. Tuples, on the other hand, are immutable, meaning that their content cannot be changed once they are created. This immutability makes tuples faster and more memory-efficient than lists for some use cases.
- Syntax: Lists are defined using square brackets
[]
, while tuples are defined using parentheses()
. You can also create a tuple without using parentheses by just separating the items with commas. - Methods: Lists have more built-in methods (e.g.,
append
,extend
,remove
,pop
, etc.) that allow you to manipulate their content. Since tuples are immutable, they have fewer built-in methods.
Here are some examples to illustrate the differences:
pythonCopy code
# Creating a list and a tuple
my_list = [1, 2, 3, 4, 5]
my_tuple = (1, 2, 3, 4, 5)
# Modifying a list (allowed)
my_list[0] = 10
print(my_list)
# Modifying a tuple (not allowed, raises TypeError)
my_tuple[0] = 10 # This line will raise a TypeError: 'tuple' object does not support item assignment
# Adding an item to the list
my_list.append(6)
print(my_list)
# Tuples don't have an 'append' method, so you cannot add items to them directly.
In summary, the main difference between lists and tuples is mutability. Lists are mutable and can be modified after creation, while tuples are immutable and cannot be modified. Consequently, use lists when you need a dynamic and modifiable data structure, and use tuples when you need a fixed and unchangeable data structure.
请登录后查看评论内容