Python:如何通过切片插入列表? [英] Python: How do you insert into a list by slicing?

查看:127
本文介绍了Python:如何通过切片插入列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被指示要防止这种情况在Python程序中发生,但是坦率地说,我什至不知道这怎么可能.有人可以举一个例子,说明如何对列表进行切片并将其插入其中以使其变大吗?谢谢

I was instructed to prevent this from happening in a Python program but frankly I have no idea how this is even possible. Can someone give an example of how you can slice a list and insert something into it to make it bigger? Thanks

推荐答案

>>> a = [1,2,3]
>>> a[:0] = [4]
>>> a
[4, 1, 2, 3]

a[:0]是列表a的切片,在任何元素之前开始,在索引0之前结束",它最初是一个空切片(因为原始列表中在索引0之前没有元素).如果将其设置为非空列表,则将使用这些元素扩展原始列表.您还可以通过指定零宽度切片(或非零宽度切片,如果您还想替换现有元素)来在列表中的其他位置执行相同的操作:

a[:0] is the "slice of list a beginning before any elements and ending before index 0", which is initially an empty slice (since there are no elements in the original list before index 0). If you set it to be a non-empty list, that will expand the original list with those elements. You could also do the same anywhere else in the list by specifying a zero-width slice (or a non-zero width slice, if you want to also replace existing elements):

>>> a[1:1] = [6,7]
>>> a
[4, 6, 7, 1, 2, 3]

这篇关于Python:如何通过切片插入列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆