【Python】切片

处理Python的部分元素,称之为切片。

创建切片

指定要是用的第一个元素和最后一个元素的索引,与range()函数一样,Python在到达你指定的第二个索引前面的元素后停止。

先定义一个列表vegetables

vegetables = ['tomato','bean','potato','onion','radish']

取出第1~3个元素

print(vegetables[0:3])

取出第2~4个元素

print(vegetables[1:4])

取出前4个元素

print(vegetables[:4])

取出第2个元素后的所有元素(包含第2个)

print(vegetables[2:])

取出最后三个元素

print(vegetables[-3:])

复制列表

要复制切片,可创建一个包含整个列表的切片,方法是同时省略起始索引和终止索引[:],这让python创建一个始于第一个元素,终止于最后一个元素的切片,即复制整个列表。

fruits = ['aplle','pear','lemon','peach']
fruits_copy = fruits[:]
print(fruitsfoot_copy)

可能从上述案例中我们还没办法看出是有2个列表,下面整个例子可以更好的说明

fruits = ['aplle','pear','lemon','peach']
fruits_copy = fruits[:]

fruits.append('grape')
fruits_copy.append('banana')

print(fruits)
print(fruits_copy)

打印结果:

['aplle', 'pear', 'lemon', 'peach', 'grape']
['aplle', 'pear', 'lemon', 'peach', 'banana']

这就说明了确实是复制了列表。

以下是一个错误的案例

fruits = ['aplle','pear','lemon','peach']
fruits_copy = fruits

fruits.append('grape')
fruits_copy.append('banana')

print(fruits)
print(fruits_copy)

打印结果:

['aplle', 'pear', 'lemon', 'peach', 'grape', 'banana']
['aplle', 'pear', 'lemon', 'peach', 'grape', 'banana']

这里将fruits赋给fruits_copy,而不是将fruits的副本存储到fruits_copy.

原文地址:https://www.cnblogs.com/OliverQin/p/7780803.html