❶ Python中列表的方法有什么
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(mostrecentcalllast):
File"",line1,in
ValueError:list.remove(x):xnotinlist
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
关于Python的基础问题可以看下这个网页的视频教程,网页链接,希望我的回答能帮到你。
❷ Python中最常用的操作列表的几种方法归纳
这里介绍几个常用的列表操作:
1、添加元素
添加元素使用列表的内置方法append
number = [1, 2, 3, 4]
number.append(5) # number = [1, 2, 3, 4, 5]
number.append([6,7]) # number = [1, 2, 3, 4, 5, [6, 7]]
number.append({'a':'b'}) # number = [1, 2, 3, 4, [6, 7], {'a', :'b'}
可以看到强大的python列表可以嵌套任意类型
2、列表相加
要想连接两个列表,可以使用+号连接
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b # c = [1, 2, 3, 4, 5, 6]
也可以使用列表内置方法extend连接两个列表
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b) # a = [1, 2, 3, 4, 5, 6]
用+号会创建一个新通对象,使用extend则在原来的对象上面修改
3、列表去重复
列表本身没有去除重复的功能,但是可以借助python的另外一个类型set(help(set)查看)
a = [1, 2, 3, 3,2, 1]
b = list(set(a)) # b = [1, 2, 3]
也可以借助字典类型的内置方法
a = [1, 2, 2, 3, 1, 3]
b = {}.fromkeys(a).keys() # b = [1, 2, 3]