Python切片:日常编码的9种实用方法

Python切片:日常编码的9种实用方法

对于每个 Python 程序员来说,无论是在数据科学和机器学习领域,还是在软件开发领域,Python 切片操作都是最高效、最通用、最强大的操作之一。Python 切片语法允许提取和修改数据结构,如列表、字符串、元组、数组、Pandas 数据帧,甚至字节序列。无论我们是要在 Python 中提取列表切片的一部分,还是使用字符串切片操作字符,或者只是想简化工作流程,切片都提供了一种简洁的数据处理方式,而无需使用复杂的循环或手动索引。在本 Python 切片教程中,我们将深入探讨 Python 切片操作的工作原理,并学习如何在程序和工作流中有效地使用它们。

什么是 Python 中的切片操作?

切片意味着切割。同样,在 Python 中,它意味着通过指定索引范围来访问或提取序列(如字符串、列表、元组或数组)的子序列(部分)。Python 中的切片操作涉及在方括号内使用冒号操作符 [:] 。基本语法包括

[START:END:STEP]START:Start 是开始切片的索引。END:End 是执行操作的索引点,即不包含在操作中。STEP: Step 是增量索引。默认值为 1,即输出整个序列。如果 step=2,则将打印每个交替值。

为什么使用切片法?

切片是一种重要的方法,因为它允许我们简洁地访问和操作数据,使代码更具可读性,并在不同的数据结构中具有通用性。例如

不使用切片的迭代

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
lst = [1, 2, 3, 4, 5]
sublist = []
for i in range(1, 4):
sublist.append(lst[i])
print(sublist)
lst = [1, 2, 3, 4, 5] sublist = [] for i in range(1, 4): sublist.append(lst[i]) print(sublist)
lst = [1, 2, 3, 4, 5]
sublist = []
for i in range(1, 4):
sublist.append(lst[i])
print(sublist)

切片迭代

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
lst = [1, 2, 3, 4, 5]
sublist = lst[1:4]
print(sublist)
lst = [1, 2, 3, 4, 5] sublist = lst[1:4] print(sublist)
lst = [1, 2, 3, 4, 5]
sublist = lst[1:4]
print(sublist)

输出:[2, 3, 4]

Python中的切片方法

基本上,Python 提供了两种不同的切片方法。一种是 [start: end: step] 函数,另一种是 .slice(start, stop, step) 函数。在本节中,我们将首先了解这些切片操作的语法,然后探讨我们可以在 Python 中执行的主要切片类型。

Python中的切片方法

1. 使用 [start: end: step] 

这是对输入序列的不同部分执行切分操作的最常用方法。

使用索引 [:] 切片示例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mixed_data = [10, "apple", 3.14, "banana", 42, "cherry"]
# Slice from index 1 to 4
print(mixed_data[1:4])
print(20*"--")
# Slice the list from the start to index 3
print(mixed_data[:3])
print(20*"--")
# Slice every 2nd element
print(mixed_data[::2])
mixed_data = [10, "apple", 3.14, "banana", 42, "cherry"] # Slice from index 1 to 4 print(mixed_data[1:4]) print(20*"--") # Slice the list from the start to index 3 print(mixed_data[:3]) print(20*"--") # Slice every 2nd element print(mixed_data[::2])
mixed_data = [10, "apple", 3.14, "banana", 42, "cherry"]
# Slice from index 1 to 4
print(mixed_data[1:4]) 
print(20*"--")
# Slice the list from the start to index 3
print(mixed_data[:3]) 
print(20*"--")
# Slice every 2nd element
print(mixed_data[::2])
['apple', 3.14, 'banana']---[10, 'apple', 3.14]---[10, 3.14, 42]

2. 使用 Python slice() 函数

slice 函数允许您创建一个将应用于序列的 slice 对象。当您想存储切片规范并将其应用于多个序列时,该功能会有所帮助。

.slice() 的语法

slice(start, stop, step)

start:切片的起始索引(包含)。stop:切片的停止索引(不包含)。step:step 或 stride(每一步后索引的增量,可选)。

使用 slice() 分割。示例:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
text = "Hello, world!"
# Create a slice object to get the first 5 characters
s = slice(0, 5)
# Apply the slice object to the string
print(text[s])
# Output: "Hello"
text = "Hello, world!" # Create a slice object to get the first 5 characters s = slice(0, 5) # Apply the slice object to the string print(text[s]) # Output: "Hello"
text = "Hello, world!"
# Create a slice object to get the first 5 characters
s = slice(0, 5)
# Apply the slice object to the string
print(text[s]) 
# Output: "Hello"

每三个元素切一次

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
mixed_data = [10, "apple", 3.14, "banana", 42, "cherry"]
s = slice(None, None, 3)
# Apply the slice object to the list
print(mixed_data[s])
# Output: [10, 'banana']
mixed_data = [10, "apple", 3.14, "banana", 42, "cherry"] s = slice(None, None, 3) # Apply the slice object to the list print(mixed_data[s]) # Output: [10, 'banana']
mixed_data = [10, "apple", 3.14, "banana", 42, "cherry"]
s = slice(None, None, 3)
# Apply the slice object to the list
print(mixed_data[s]) 
# Output: [10, 'banana']

从索引 2 开始切到末端

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
s = slice(2, None)
# Apply the slice object to the list
print(mixed_data[s])
# Output: [3.14, 'banana', 42, 'cherry']
s = slice(2, None) # Apply the slice object to the list print(mixed_data[s]) # Output: [3.14, 'banana', 42, 'cherry']
s = slice(2, None)
# Apply the slice object to the list
print(mixed_data[s]) 
# Output: [3.14, 'banana', 42, 'cherry']

按相反顺序切片

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
s = slice(None, None, -1)
# Apply the slice object to the list
print(mixed_data[s])
# Output: ['cherry', 42, 'banana', 3.14, 'apple', 10]
s = slice(None, None, -1) # Apply the slice object to the list print(mixed_data[s]) # Output: ['cherry', 42, 'banana', 3.14, 'apple', 10]
s = slice(None, None, -1)
# Apply the slice object to the list
print(mixed_data[s]) 
# Output: ['cherry', 42, 'banana', 3.14, 'apple', 10]

现在我们来看看 Python 中主要的切片操作类型

1. 基本切片

基本切分是指使用语法 [start: end: step] 提取字符串、列表或元组等数据类型的子序列。它是 Python 中的一个基本工具,能让我们轻松检索子序列。它还适用于多种数据类型,因此是一种通用技术。

  • List 切片
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Slice from index 1 to index 4 (exclusive)
print(numbers[1:4])
# Output: [20, 30, 40]
numbers = [10, 20, 30, 40, 50, 60] # Slice from index 1 to index 4 (exclusive) print(numbers[1:4]) # Output: [20, 30, 40]
numbers = [10, 20, 30, 40, 50, 60]
# Slice from index 1 to index 4 (exclusive)
print(numbers[1:4]) 
# Output: [20, 30, 40]
  • String 切片
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
text = "Hello, world!"
# Slice from index 7 to index 12 (exclusive)
print(text[7:12])
# Output: "world"
text = "Hello, world!" # Slice from index 7 to index 12 (exclusive) print(text[7:12]) # Output: "world"
text = "Hello, world!"
# Slice from index 7 to index 12 (exclusive)
print(text[7:12]) 
# Output: "world"
  • Tuple 切片
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers_tuple = (1, 2, 3, 4, 5, 6)
# Slice from index 2 to index 5 (exclusive)
print(numbers_tuple[2:5])
# Output: (3, 4, 5)
numbers_tuple = (1, 2, 3, 4, 5, 6) # Slice from index 2 to index 5 (exclusive) print(numbers_tuple[2:5]) # Output: (3, 4, 5)
numbers_tuple = (1, 2, 3, 4, 5, 6)
# Slice from index 2 to index 5 (exclusive)
print(numbers_tuple[2:5]) 
# Output: (3, 4, 5)

2. 省略‘start’, ‘stop’, 或‘step’

在切片中省略开始、停止和步长可以让用户使用默认值。

  • 省略开始默认为序列的开始。
  • 省略停止表示切片一直进行到结束。
  • 省略步长则默认步长为 1。

省略这些部分可以使代码更简洁、更灵活。它使你能够创建动态和通用的切片,而无需明确定义所有参数。

使用切片修改列表

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Omitting start, slice from the beginning to index 4 (exclusive)
print(numbers[:4])
# Output: [10, 20, 30, 40]
# Omitting stop, slice from index 2 to the end
print(numbers[2:])
# Output: [30, 40, 50, 60]
numbers = [10, 20, 30, 40, 50, 60] # Omitting start, slice from the beginning to index 4 (exclusive) print(numbers[:4]) # Output: [10, 20, 30, 40] # Omitting stop, slice from index 2 to the end print(numbers[2:]) # Output: [30, 40, 50, 60]
numbers = [10, 20, 30, 40, 50, 60]
# Omitting start, slice from the beginning to index 4 (exclusive)
print(numbers[:4]) 
# Output: [10, 20, 30, 40]
# Omitting stop, slice from index 2 to the end
print(numbers[2:]) 
# Output: [30, 40, 50, 60]

空切片

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers_tuple = (1, 2, 3, 4, 5, 6)
# Omitting start and step, slice the whole tuple
print(numbers_tuple[:])
# Output: (1, 2, 3, 4, 5, 6)
numbers_tuple = (1, 2, 3, 4, 5, 6) # Omitting start and step, slice the whole tuple print(numbers_tuple[:]) # Output: (1, 2, 3, 4, 5, 6)
numbers_tuple = (1, 2, 3, 4, 5, 6)
# Omitting start and step, slice the whole tuple
print(numbers_tuple[:]) 
# Output: (1, 2, 3, 4, 5, 6)

删除元素

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [2,4,5,12,64,45]
numbers[1:4] = []
print(numbers)
# Output: [2,64,45]
numbers = [2,4,5,12,64,45] numbers[1:4] = [] print(numbers) # Output: [2,64,45]
numbers = [2,4,5,12,64,45]
numbers[1:4] = []
print(numbers)
# Output: [2,64,45]

3. 负切片

负索引允许从序列末尾开始计数。在负索引中,-1 表示最后一个元素,-2 表示倒数第二个元素。当你需要访问序列末尾的元素时,它可以帮助你。

访问最后一个元素

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Slice at the last index
print(numbers[-1])
# Output: [60]
numbers = [10, 20, 30, 40, 50, 60] # Slice at the last index print(numbers[-1]) # Output: [60]
numbers = [10, 20, 30, 40, 50, 60]
# Slice at the last index
print(numbers[-1]) 
# Output: [60]

反转字符串

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
original_string = "hello"
reversed_string = original_string[::-1]
print(reversed_string)
# Output: "olleh"
original_string = "hello" reversed_string = original_string[::-1] print(reversed_string) # Output: "olleh"
original_string = "hello"
reversed_string = original_string[::-1]
print(reversed_string) 
# Output: "olleh"

4. 使用步长进行切片

步长参数可以指定元素之间的间隔,这在处理或采样数据时非常有用。如上图所示,负步长可以很容易地逆转序列,这使得逆转整个数据变得非常简单方便。

每隔 2 个元素切片

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Slice with step 2, picking every second element
print(numbers[::2])
# Output: [10, 30, 50]
numbers = [10, 20, 30, 40, 50, 60] # Slice with step 2, picking every second element print(numbers[::2]) # Output: [10, 30, 50]
numbers = [10, 20, 30, 40, 50, 60]
# Slice with step 2, picking every second element
print(numbers[::2]) 
# Output: [10, 30, 50]

混乱的步长行为

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Slice at last index
print(numbers[::-3])
# Output: [60,30]
numbers = [10, 20, 30, 40, 50, 60] # Slice at last index print(numbers[::-3]) # Output: [60,30]
numbers = [10, 20, 30, 40, 50, 60]
# Slice at last index
print(numbers[::-3]) 
# Output: [60,30]

5. 使用 None 进行切片

在切片中,None 可用于表示开始、停止和结束的默认值。使用 None 可以使编程更灵活、更清晰。这是一种无需手动定义即可应用默认切片行为的方法。

省略使用 None

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Slice every 2nd element using slice(None, None, 2)
s = slice(None, None, 2)
print(numbers[s])
# Output: [10, 30, 50]
numbers = [10, 20, 30, 40, 50, 60] # Slice every 2nd element using slice(None, None, 2) s = slice(None, None, 2) print(numbers[s]) # Output: [10, 30, 50]
numbers = [10, 20, 30, 40, 50, 60]
# Slice every 2nd element using slice(None, None, 2)
s = slice(None, None, 2)
print(numbers[s]) 
# Output: [10, 30, 50]

6. 越界切片

当您尝试对一个序列进行超出其边界的切分时(无论是使用大索引还是使用超出范围的 -ve 索引),Python 不会引发任何错误,只会返回最大的有效切分,而不用担心异常。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
numbers = [10, 20, 30, 40, 50, 60]
# Slice beyond the length of the list
print(numbers[4:15])
# Output: [50, 50]
numbers = [10, 20, 30, 40, 50, 60] # Slice beyond the length of the list print(numbers[4:15]) # Output: [50, 50]
numbers = [10, 20, 30, 40, 50, 60]
# Slice beyond the length of the list
print(numbers[4:15]) 
# Output: [50, 50]

超长切片

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
text = "Hello, world!"
# Slice beyond the length
print(text[15:55])
# Output: no output
text = "Hello, world!" # Slice beyond the length print(text[15:55]) # Output: no output
text = "Hello, world!"
# Slice beyond the length
print(text[15:55])
# Output: no output

7. NumPy数组切片

在 NumPy 中,切片与 Python 的基本切片类似。此外,NumPy 是专为科学计算而设计的,也允许更快的数据操作。这有助于进一步支持更先进、更高效的大型数据集操作。切片使 NumPy 能够访问子数组并高效地修改它们(即允许我们修改子数组)。

切片一维数组

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import numpy as np
# Create a 1-D NumPy array
arr = np.array([10, 20, 30, 40, 50, 60])
# Slice from index 1 to index 4 (exclusive)
print(arr[1:4])
# Output: [20 30 40]
import numpy as np # Create a 1-D NumPy array arr = np.array([10, 20, 30, 40, 50, 60]) # Slice from index 1 to index 4 (exclusive) print(arr[1:4]) # Output: [20 30 40]
import numpy as np
# Create a 1-D NumPy array
arr = np.array([10, 20, 30, 40, 50, 60])
# Slice from index 1 to index 4 (exclusive)
print(arr[1:4]) 
# Output: [20 30 40]

与基本的切片一样,它允许我们从索引 1 到 4(排他)对数组进行切片,就像普通的 Python 切片一样。它还允许在数组中执行上面讨论过的所有其他操作。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Slice every second element from the array
print(arr[::2])
# Output: [10 30 50]
# Slice every second element from the array print(arr[::2]) # Output: [10 30 50]
# Slice every second element from the array
print(arr[::2]) 
# Output: [10 30 50]

切片多维数组

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create a 2-D NumPy array (matrix)
arr_2d = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Slice from row 1 to row 2 (exclusive), and columns 1 to 2 (exclusive)
print(arr_2d[1:2, 1:3])
# Output: [[50 60]]
# Create a 2-D NumPy array (matrix) arr_2d = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]]) # Slice from row 1 to row 2 (exclusive), and columns 1 to 2 (exclusive) print(arr_2d[1:2, 1:3]) # Output: [[50 60]]
# Create a 2-D NumPy array (matrix)
arr_2d = np.array([[10, 20, 30], [40, 50, 60], [70, 80, 90]])
# Slice from row 1 to row 2 (exclusive), and columns 1 to 2 (exclusive)
print(arr_2d[1:2, 1:3]) 
# Output: [[50 60]]

8. Pandas数据帧切片

Pandas DataFrames 是二维标签数据结构,也支持切片操作。它允许通过 .loc() 和 .iloc() 对数据点进行切分。此外,Pandas 还支持布尔索引。

对数据帧本身进行切片可以高效地过滤和处理大型数据集。它允许使用条件选择数据子集,使其成为数据分析和机器学习的重要工具。

使用行索引(.iloc)进行切片

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50]
})
print(df)
# Output
# A B
# 0 1 10
# 1 2 20
# 2 3 30
# 3 4 40
# 4 5 50
# Slice the first three rows (exclusive of the fourth row)
print(df.iloc[:3])
# A B
# 0 1 10
# 1 2 20
# 2 3 30
import pandas as pd # Create a DataFrame df = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50] }) print(df) # Output # A B # 0 1 10 # 1 2 20 # 2 3 30 # 3 4 40 # 4 5 50 # Slice the first three rows (exclusive of the fourth row) print(df.iloc[:3]) # A B # 0 1 10 # 1 2 20 # 2 3 30
import pandas as pd
# Create a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50]
})
print(df)
# Output
#    A   B
# 0  1  10
# 1  2  20
# 2  3  30
# 3  4  40
# 4  5  50
# Slice the first three rows (exclusive of the fourth row)
print(df.iloc[:3])
#    A   B
# 0  1  10
# 1  2  20
# 2  3  30

在这里,.iloc(3) 会切分 DataFrame 的前 3 行(索引 0 至 2)。

使用列名(.loc)切片

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# Create a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50]
})
print(df)
# Output
# A B
# 0 1 10
# 1 2 20
# 2 3 30
# 3 4 40
# 4 5 50
print(df.loc[df['A'] > 2])
# Output:
# A B
# 2 3 30
# 3 4 40
# 4 5 50
# Create a DataFrame df = pd.DataFrame({ 'A': [1, 2, 3, 4, 5], 'B': [10, 20, 30, 40, 50] }) print(df) # Output # A B # 0 1 10 # 1 2 20 # 2 3 30 # 3 4 40 # 4 5 50 print(df.loc[df['A'] > 2]) # Output: # A B # 2 3 30 # 3 4 40 # 4 5 50
# Create a DataFrame
df = pd.DataFrame({
'A': [1, 2, 3, 4, 5],
'B': [10, 20, 30, 40, 50]
})
print(df)
# Output
#    A   B
# 0  1  10
# 1  2  20
# 2  3  30
# 3  4  40
# 4  5  50
print(df.loc[df['A'] > 2]) 
# Output:
#    A   B
# 2  3  30
# 3  4  40
# 4  5  50

.loc 允许使用列名或索引(如 False)对标签进行切分。在这里,我们根据列“A”的值必须大于 2 的条件进行切分。

9. 字节序列切片

Python 提供了字节序列(如 bytes 和 bytearray),它们与列表、字符串或数组一样支持切片。当我们使用二进制数据类型时,字节序列就会出现,而切片可以让您轻松高效地提取二进制数据的相关部分。

切分字节对象

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
byte_seq = b'Hello, world!'
# Slice from index 0 to index 5 (exclusive)
print(type(byte_seq))
print(byte_seq[:5])
# Output: <class 'bytes'>, b'Hello'
byte_seq = b'Hello, world!' # Slice from index 0 to index 5 (exclusive) print(type(byte_seq)) print(byte_seq[:5]) # Output: <class 'bytes'>, b'Hello'
byte_seq = b'Hello, world!'
# Slice from index 0 to index 5 (exclusive)
print(type(byte_seq))
print(byte_seq[:5]) 
# Output: <class 'bytes'>, b'Hello'

分割字节数组(可变字节)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
byte_arr = bytearray([10, 20, 30, 40, 50, 60])
# Slice from index 2 to index 5 (exclusive)
print(byte_arr[2:5])
# Output: bytearray(b'2\x1e<')
byte_arr = bytearray([10, 20, 30, 40, 50, 60]) # Slice from index 2 to index 5 (exclusive) print(byte_arr[2:5]) # Output: bytearray(b'2\x1e<')
byte_arr = bytearray([10, 20, 30, 40, 50, 60])
# Slice from index 2 to index 5 (exclusive)
print(byte_arr[2:5]) 
# Output: bytearray(b'2\x1e<')

在这里,输出值与 ASCII 字符相对应。当输出不在可打印范围内时,就会出现这种情况。因此,bytearray(b’2\x1e<‘) 是输出结果,因为它以更易于人类阅读的形式表示这些字节值。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
print(list(byte_arr[2:5])) # Output: [30, 40, 50]
# Ouput: [30,40,50]
print(list(byte_arr[2:5])) # Output: [30, 40, 50] # Ouput: [30,40,50]
print(list(byte_arr[2:5]))  # Output: [30, 40, 50]
# Ouput: [30,40,50]

在Python中使用切分操作的好处

在 Python 中使用切分操作有很多好处,其中包括

  • 效率高:切片操作可以快速访问较大数据集中的所需子序列,而无需循环。
  • 简洁:它使数据操作的代码更简洁、更易读。
  • 灵活性:在 NumPy 和 Pandas 等库的帮助下,多维数据切分为数据预处理提供了一种高效的方法。
  • 高效内存:切片处理经过了性能优化。此外,Python 的内部机制确保了切片操作的快速性和内存效率,这与手动索引不同,手动索引需要大量的手动编码并会增加内存使用量。

使用切分操作时应避免的事项

以下是在 Python 中使用切分操作时应避免的几件事。

  • 超出索引边界:在 Python 中,超出序列长度的切分不会导致任何错误。然而,这会导致不必要的结果,尤其是在处理较大的数据集时。
  • 混淆索引和切片语法:切片语法涉及 sequence[start:stop:end],但选择我们想要的元素的索引/位置也会得到想要的元素。
  • 不考虑可变性的切分:切分可用于修改序列,但使用时必须考虑所处理的数据类型是否支持可变性。例如,列表和字节数组是可变的;而字符串、元组和字节则是不可变的。因此无法通过切片直接修改它们。
  • 使用无效步骤值进行切片:在使用切片时,还必须考虑步长,因为步长将决定中间跳过多少个点。但使用无效值可能会导致意想不到的结果,造成操作效率低下。

小结

Python 中的切片是一种高效而强大的方法,它允许您有效地访问和操作 Python 数据类型,如列表、字符串、元组、NumPy 数组和 Pandas DataFrames。因此,无论您是对列表进行切片,还是使用 NumPy 处理多维数组,或者使用 Pandas 处理大型数据集,切片总是能为处理序列提供一种清晰简洁的方法。掌握了切片,就能编写出更简洁、更高效的代码,这对每个 Python 程序员来说都是必不可少的。

评论留言