首页 技术 正文
技术 2022年11月19日
0 收藏 693 点赞 4,216 浏览 1065 个字

处理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.

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903