从列表中获取元素
与数组一致,通过元素的索引值index从列表获取单个元素,注意,列表索引都是从0开始的。
>>> number = ['阿里巴巴','华为','linux','123','cisco','IBM']
>>> temp = number[0]
>>> number[0] = number[1]
>>> number[1] = temp
>>> number
['华为', '阿里巴巴', 'linux', '123', 'cisco', 'IBM']
>>> number[3]
'123'
从列表删除元素
remove
>>> number.remove('华为')
>>> number
['阿里巴巴', 'linux', '123', 'cisco', 'IBM']
>>>
del()
>>> del number[1]
>>> number
['阿里巴巴', '123', 'cisco', 'IBM']
>>>
pop
>>> number.pop()
'IBM'
>>> number
['阿里巴巴', '123', 'cisco']
>>> name = number.pop()
>>> name
'cisco'
>>> number
['阿里巴巴', '123']
>>>
当然也可以加入索引值
>>> name = number.pop(1)
>>> name
'123'
>>> number
['阿里巴巴']
列表分片
利用索引值,每次获取对应的元素,那么如果想获取多个元素呢?利用列表分片即可
>>> number = ['阿里巴巴','华为','linux','123','cisco','IBM']
>>> number[1:3]
['华为', 'linux']
>>> number
['阿里巴巴', '华为', 'linux', '123', 'cisco', 'IBM']
列表分片左边开始为1,结束为3,但是不包含3,而原列表是不会发生改变的。
>>>
```python
number
['阿里巴巴', '华为', 'linux', '123', 'cisco', 'IBM']
number[:3]
[‘阿里巴巴’, ‘华为’, ‘linux’]number[2:]
[‘linux’, ‘123’, ‘cisco’, ‘IBM’]number2 = number[2:]
number2
[‘linux’, ‘123’, ‘cisco’, ‘IBM’]
课后题:
0. 下边的列表分片操作会打印什么内容?
```python
>>> list1 = [1, 3, 2, 9, 7, 8]
>>> list1[2:5]
解:2,9,7
-
请问 list1[0] 和 list1[0:1] 一样吗?
解:不一样,list1[0] 返回第0个元素的值,list1[0:1] 返回一个只含有第0个元素的列表。 -
如果你每次想从列表的末尾取出一个元素,并将这个元素插入到列表的最前边,你会怎么做?
解:两步,取出来,插入
>>> number = ['阿里巴巴', '华为', 'linux', '123', 'cisco', 'IBM']
>>> number.insert(0,number.pop())
>>> number
['IBM', '阿里巴巴', '华为', 'linux', '123', 'cisco']
- 试试 number[-3:-1] 会不会报错,这是怎么回事呢?
解:正常索引是从左到右索引,负数索引是从右到左
>>> number
['IBM', '阿里巴巴', '华为', 'linux', '123', 'cisco']
>>> number[-3:-1]
['linux', '123']
- 在进行分片的时候,我们知道分片的开始和结束位置需要进行指定,但其实还有另外一个隐藏的设置:步长。
解:
- 之前提到的“简洁”分片操作在这里有效:
>>> number
['IBM', '阿里巴巴', '华为', 'linux', '123', 'cisco']
>>> number[::2]
['IBM', '华为', '123']
- 步长不能为0,要不就走不动了:
>>> number[::0]
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
number[::0]
ValueError: slice step cannot be zero
- 步长可以是负数,改变方向(从尾部开始向左走):
>>> number[::-2]
['cisco', 'linux', '阿里巴巴']
- 可以利用分片完成列表的拷贝 listr2 = list1[:],那事实上可不可以直接写成 list2 = list1 更加简洁呢?
解:不可以
>>> list1 = [1,3,2,9,7,8]
>>> list2 = list1[ : ]
>>> list2
[1, 3, 2, 9, 7, 8]
>>> list3 = list1
>>> list3
[1, 3, 2, 9, 7, 8]
>>> list1.sort()
>>> list1
[1, 2, 3, 7, 8, 9]
>>> list2
[1, 3, 2, 9, 7, 8]
>>> list3
[1, 2, 3, 7, 8, 9]
在为一个固定的东西指定另一个名字的做法,只是向同一个东西增加一个新的标签而已