python中用slice修改元素的方法
小编给大家分享一下python中用slice修改元素的方法,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
在列表中常用到切割的思想,对数列进行分离,这就是小编本篇要着重讲到的slice函数。一般我们提到slice会习惯性的使用切割的方法,在使用上就不能完成发挥它的作用。其实我们完全可以用slice对序列里的元素进行修改和删除,毕竟同切割一样与序列的关系密不可分。
1.切片语法列表
# https://*.com/questions/509211/understanding-slice-notation # 切片的形式(stride > 0) >>> seq[:] # [seq[0], seq[1], ..., seq[-1] ] >>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ] >>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]] >>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]] >>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ] >>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ] >>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]] >>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]] # 切片的形式(stride < 0) >>> seq[::-stride] # [seq[-1], seq[-1-stride], ..., seq[0] ] >>> seq[high::-stride] # [seq[high], seq[high-stride], ..., seq[0] ] >>> seq[:low:-stride] # [seq[-1], seq[-1-stride], ..., seq[low+1]] >>> seq[high:low:-stride] # [seq[high], seq[high-stride], ..., seq[low+1]]
2.修改序列/元素、删除序列元素
切片除了可以查找序列中的元素之外,还有一些重要的功能就是修改序列/元素、删除序列元素。
# 修改 l = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'] l[1:4] = [1, 2, 3] # 修改后结果为:['a', 1, 2, 3, 'e', 'f', 'g', 'h', 'i'] l[1:2] = [1, 2, 3] # 修改/替换后的结果为:['a', 1, 2, 3, 2, 3, 'e', 'f', 'g', 'h', 'i'] # 插入 l = ['a', 'b', 'c'] l[:0] = [1, 2, 3] # 插入后结果为:[1, 2, 3, 'a', 'b', 'c'] l = ['a', 'b', 'c'] l[len(l):] = [1, 2, 3] # 插入后结果为:['a', 'b', 'c', 1, 2, 3] l = ['a', 'b', 'c'] l[1:1] = [1, 2, 3] # 插入后结果为:['a', 1, 2, 3, 'b', 'c'] # 删除 l = ['a', 'b', 'c', 'd', 'e'] l[1:5] = [] # 删除后结果为:['a'] # 还可以用 del 语句删除序列中的部分元素 l = ['a', 'b', 'c', 'd', 'e'] del l[1:5] # 删除后结果为:['a'],效果一样
以上是“python中用slice修改元素的方法”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注行业资讯频道!