Python 索引和切片的区别

Python 索引和切片的区别

在这篇文章中,我们将向您解释Python中索引和切片的区别。

索引和切片仅适用于序列数据类型。序列类型中插入元素的顺序被保留,允许我们通过索引和切片访问其元素。

总结一下,Python的序列类型包括列表、元组、字符串、范围、字节和字节数组。索引和切片适用于所有这些类型。

索引

术语“索引”是指根据迭代对象内部的位置来引用一个元素。

索引从0开始。序列中的第一个元素由索引0表示。

负索引从-1开始。序列中的最后一个元素由索引-1表示。

字符串中的每个字符对应一个索引号,可以根据其索引号访问每个字符。有两种访问字符串字符的方法。

  • 使用正索引访问字符串字符

  • 使用负索引访问字符串字符

                     T  U  T  O  T  I  A  L  S
Positive Indexing    0  1  2  3  4  5  6  7  8
Negative indexing   -9 -8 -7 -6 -5 -4 -3 -2 -1

使用正索引访问字符串字符

在这种情况下,我们在方括号中传递一个正索引(我们希望访问的索引)。索引号序列从索引号0开始(表示字符串的第一个字符)。

示例

# input string
inputString = "Hello tutorialspoint python"

print("0th index character:", inputString[0])
print("7th index character", inputString[7])

print("12th index character:", inputString[12])
('0th index character:', 'H')
('7th index character', 'u')
('12th index character:', 'a')

输出

0th index character: H
7th index character u
12th index character: a

使用负索引访问字符串字符

在这种类型的索引中,我们将希望访问的负索引号放在方括号中。在这种情况下,索引号从-1开始(表示字符串的最后一个字符)。

示例

# input string
inputString = "Hello tutorialspoint python"
print("last index character:", inputString[-1])
print("6th index character from last:", inputString[-6])
('last index character:', 'n')
('6th index character from last:', 'p')

输出

last index character: n
6th index character from last: p

列表中的索引

示例

# input list
inputList =[1, 4, 8, 6, 2]
print("Element at index 2:", inputList[2])
print("last element of an input list:", inputList[-1])
('Element at index 2:', 8)
('last element of an input list:', 2)

输出

Element at index 2: 8
last element of an input list: 2

注意事项

当我们尝试使用一个不存在或太大的索引时,它会抛出一个 IndexError

示例

# input list
inputList =[1, 4, 8, 6, 2]
# printing the element at index 10 of a input list
# throws an IndexError as the index 10 doesn't exist in the input list
print("Element at index 10:", inputList[10])
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print("Element at index 10:", inputList[10])
IndexError: list index out of range

输出

Traceback (most recent call last):
File "main.py", line 5, in <module>
print("Element at index 10:", inputList[10])
IndexError: list index out of range

切片

术语“ 切片 ”是指根据索引从可迭代对象中获取一部分元素的过程。

我们通过切片字符串来创建子字符串,这实际上是一个存在于另一个字符串中的字符串。当我们只需要字符串的一部分而不是整个字符串时,我们使用切片。

语法

string[start : end : step]

参数

start - index from where to start
end - ending index
step - numbers of jumps/increment to take between i.e stepsize

字符串中的切片

# input string
inputString = "Hello tutorialspoint python"
print("First 4 characters of the string:", inputString[: 4])
print("Alternate characters from 1 to 10 index(excluded):", inputString[1 : 10 : 2])
print("Alternate characters in reverse order from 1 to 10 index(excluded):", inputString[-1 : -10 : -2])
('First 4 characters of the string:', 'Hell')
('Alternate characters from 1 to 10 index(excluded):', 'el uo')
('Alternate characters in reverse order from 1 to 10 index(excluded):', 'nhy n')

输出

First 4 characters of the string: Hell
Alternate characters from 1 to 10 index(excluded): el uo
Alternate characters in reverse order from 1 to 10 index(excluded): nhy n

元组切片

我们可以使用元组切片。它类似于我们如何使用字符串和列表。元组切片用于获取各种项目。我们还使用切片运算符进行元组切片。切片运算符可以通过以下语法表示:

语法

[start:stop:step]

示例

# Input tuple
givenTuple = ("Welcome", "this", "is", "TutorialsPoint", "Website", 10)
# Slicing with start and stop values(indices)
print('Tuple slicing from index 1 to index 6 :', givenTuple[1:6])
# Slicing with only stop values(indices)
print("Tuple slicing till index 7: ", givenTuple[:7])
# Slicing with only start value(indices)
print("Tuple slicing from index 2 is:", givenTuple[2:])
# Slicing without any start and stop values
print("Tuple slicing without any start and stop values:", givenTuple[:])
# Slicing in reverse order
print("Tuple slicing in reverse order:", givenTuple[::-1])
('Tuple slicing from index 1 to index 6 :', ('this', 'is', 'TutorialsPoint', 'Website', 10))
('Tuple slicing till index 7: ', ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10))
('Tuple slicing from index 2 is:', ('is', 'TutorialsPoint', 'Website', 10))
('Tuple slicing without any start and stop values:', ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10))
('Tuple slicing in reverse order:', (10, 'Website', 'TutorialsPoint', 'is', 'this', 'Welcome'))

输出

Tuple slicing from index 1 to index 6 : ('this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing till index 7:  ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing from index 2 is: ('is', 'TutorialsPoint', 'Website', 10)
Tuple slicing without any start and stop values: ('Welcome', 'this', 'is', 'TutorialsPoint', 'Website', 10)
Tuple slicing in reverse order: (10, 'Website', 'TutorialsPoint', 'is', 'this', 'Welcome')

索引与切片的区别

下表显示了Python中索引和切片之间的主要区别 –

索引 切片
只返回一个元素 返回一个新的列表/元组
如果尝试使用一个过大的索引,将抛出IndexError错误。 在使用切片时,超出范围的索引会被处理得比较温柔。
无法通过索引的元素赋值来改变列表的长度。 通过对切片赋值可以改变列表的长度甚至清空它。
可以对索引分配一个单个元素或可迭代对象。 当我们对切片分配一个单个元素时,会得到TypeError错误。它只接受可迭代对象。

结论

通过示例,我们了解了 Python 中索引和切片的区别。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程