python中如何用slice修改元素?

596次阅读
没有评论
python中如何用slice修改元素?

在列表中常用到切割的思想,对数列进行分离,这就是小编本篇要着重讲到的slice函数。一般我们提到slice会习惯性的使用切割的方法,在使用上就不能完成发挥它的作用。其实我们完全可以用slice对序列里的元素进行修改和删除,毕竟同切割一样与序列的关系密不可分。下面我们就python中用slice修改元素的方法给大家带来分享。

1.切片语法列表

# https://stackoverflow.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修改元素的方法,同时也可以进行元素的删除,小伙伴们可以两个使用功能分别尝试下代码。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-15发表,共计1846字。
新手QQ群:570568346,欢迎进群讨论 Python51学习