python3列表的函数 python中列表的用法

请问Python3中创建列表有哪些方法Python中的列表内建了许多方法 。在下文中,使用“L”代表一个列表 , 使用“x”代表方法的参数,以便说明列表的使用方法 。
1 append()方法
列表的append()方法用于将一个项添加到列表的末尾,L.append(x)等价于L[len(L):] = [x] 。
例如,使用append()方法分别将'cow'和'elephant'添加到animals列表的末尾:
animals = ['cat', 'dog', 'fish', 'dog']
animals.append('cow')# 等价于animals[4:]=['cow']
animals
['cat', 'dog', 'fish', 'dog', 'cow']
animals.append('elephant')# 等价于animals[5:]=['elephant']
animals
['cat', 'dog', 'fish', 'dog', 'cow', 'elephant']
2 ()方法
列表的()方法用于将一个项插入指定索引的前一个位置 。L.(0, x)是将x插入列表的最前面 , L.(len(L)), x)等价于L.append(x) 。
例如,使用()方法分别将'cow'和'elephant'插入animals列表:
animals =['cat', 'dog', 'fish', 'dog']
animals.(0, 'cow')
animals
['cow', 'cat', 'dog', 'fish', 'dog']
animals.(3, 'elephant')
animals
['cow', 'cat', 'dog', 'elephant', 'fish', 'dog']
3 extend()方法
列表的extend()方法用于将可迭代对象的所有项追加到列表中 。L.extend(iterable)等价于L[len(L):] = iterable 。extend()和append()方法的区别是,extend()方法会将可迭代对象“展开” 。
例如 , 分别使用append()方法和extend()方法在animals列表后面追加一个包含'cow'和'elephant'的列表:
animals = ['cat', 'dog', 'fish', 'dog']
animals.append(['cow', 'elephant'])# 此处append()参数是一个列表
animals
['cat', 'dog', 'fish', 'dog', ['cow', 'elephant']]
animals = ['cat', 'dog', 'fish', 'dog']
animals.extend(['cow', 'elephant'])# 此处extend()参数也是一个列表
animals
['cat', 'dog', 'fish', 'dog', 'cow', 'elephant']
4 remove()方法
列表的remove()方法用于移除列表中指定值的项 。L.remove(x)移除列表中第一个值为x的项 。如果没有值为x的项,那么会抛出ValueError异常 。
例如,使用remove()方法移除animals列表中值为'dog'的项:
animals = ['cat', 'dog', 'fish', 'dog']
animals.remove('dog')
animals
['cat', 'fish', 'dog']
animals.remove('dog')
animals
['cat', 'fish']
animals.remove('dog')
Traceback (most recent call last):
File "", line 1, in
ValueError: list.remove(x): x not in list
5 pop()方法
列表的pop()方法用于移除列表中指定位置的项,并返回它 。如果没有指定位置 , 那么L.pop()移除并返回列表的最后一项 。
例如,使用pop()方法移除animals列表中指定位置的项:
animals = ['cat', 'dog', 'fish', 'dog']
animals.pop()
'dog'
animals
['cat', 'dog', 'fish']
animals.pop(2)
'fish'
animals
['cat', 'dog']
在调用前面的列表方法后 , 并没有打印任何值,而pop()方法打印了“弹出”的值 。包括append()、()、pop()在内的方法都是“原地操作” 。原地操作(又称为就地操作)的方法只是修改了列表本身,并不返回修改后的列表 。
在类型转换时使用的int()函数,str()函数都有返回值:
number = 123
mystring = str(number)# 将返回值赋给变量mystring
mystring
'123'
但是在使用“原地操作”时,大部分则不会有返回值 , 包括pop()方法也只是返回了被“弹出”的值,并没有返回修改后的列表:
animals = ['cat', 'dog', 'fish', 'dog']
new_animals = animals.append('cow')
print(new_animals)
None
关于深度学习的基础问题可以看下这个网页的视频教程,网页链接 , 希望我的回答能帮到你 。

推荐阅读