|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
一、问:如果你每次想从列表的末尾取出一个元素,并将这个元素插入到列表的最前边,你会怎么做?
标准答案是:list1.insert(0, list1.pop())
但是我没想到pop方法,于是我是这样写的:
- >>> list1 = [0,1,2,3]
- >>> list1 = (list1[0:3]).insert(0,list1[3])
- >>> list1
- >>>
复制代码
输入命令,没有报错,但出乎意料的是 当我输入命令list1 打印出列表时候,什么都没有。连一个空列表都不是。
于是我用命令 type(list1) 打印出类型.
- >>> type(list1)
- <class 'NoneType'>
复制代码
'NoneType'??????!! 这是什么鬼.
还是不甘心,于是我将这个式子进行分解操作,理所应当的报错了。(因为索引值3不存在)
- >>> list1 = [0,1,2,3]
- >>> list1 = list1[0:3]
- >>> list1
- [0, 1, 2]
- >>> list1 = list1.insert(0,list1[3])
- Traceback (most recent call last):
- File "<pyshell#25>", line 1, in <module>
- list1 = list1.insert(0,list1[3])
- IndexError: list index out of range
复制代码
二、索引值越界这让我想到了另外一个问题。
- >>> number
- [1, 2, 3, 4, 5, 6]
- >>> number.insert(6,7)
- >>> number
- [1, 2, 3, 4, 5, 6, 7]
- >>> number.insert(8,8)
- >>> number
- [1, 2, 3, 4, 5, 6, 7, 8]
- >>> number.insert(8,9)
- >>> number
- [1, 2, 3, 4, 5, 6, 7, 8, 9]
- >>> number.insert(88888,10)
- >>> number
- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
复制代码
在列表最后添加一个数可以用append()方法,但是我就喜欢用insert()方法。各位鱼油,你看哪怕我的索引值写成8888,也不会报错。
我还想我索引值写8的时候没报错,会不会把8这个位置的索引值给占用了,所以会有insert(8,8);insert(8,9);然而并不会报错。emmmm
1. 按你的思路应该是:
>>> list1 = [0,1,2,3]
>>> list2 = list1[0:3]
>>> list2.insert(0,list1[3])
>>> list2
[3, 0, 1, 2]
2. 抄录一段话: https://www.cnblogs.com/huangbiquan/p/7863056.html
场景1:index=0时,从头部插入obj
场景2:index > 0 且 index < len(list)时,在index的位置插入obj
场景3:当index < 0 且 abs(index) < len(list)时,从中间插入obj,如: -1 表示从倒数第1位插入obj; -2 表示从倒数第1位插入obj
场景4:当index < 0 且 abs(index) >= len(list)时,从头部插入obj
场景5:当index >= len(list)时,从尾部插入obj
|
|