Python中append()和extend()的区别,pop()和remove()的区别

来源:互联网 发布:mysql having的用法 编辑:程序博客网 时间:2024/06/05 06:30

1. list 中 append()和extend()的区别    

    (1) L.append(object) -> None -- append object to end 

          append(object) 是将一个对象作为一个整体添加到列表中,添加后的列表比原列表多一个元素,该函数的参数可以是任何类型的对象,该函数没有返回值          

    (2) L.extend(iterable) -> None -- extend list by appending elements from the iterab

          extend(iterable) 是将一个可迭代对象中的每个元素逐个地添加到列表中,可迭代对象中有几个元素,添加后的列表就比原列表多几个元素,该函数的参数必须是可

                                       迭代的对 象,改函数没有返回值

          

>>> listA = [1, 2, 3]>>> listB = [4, 5, 6]>>> listA.append(listB)>>> print(listA)[1, 2, 3, [4, 5, 6]]>>> listA.extend(listB)[1, 2, 3, [4, 5, 6], 4, 5, 6]>>> listB.append(7)>>> print(listB)[4, 5, 6, 7]>>> listB.append({'a':97, 'b':98})>>> print(listB)[4, 5, 6, 7, {'a': 97, 'b': 98}]>>> listB.extend('def')>>> print(listB)[4, 5, 6, 7, {'a': 97, 'b': 98}, 'd', 'e', 'f']

2. list 中pop()和remove()的区别

   (1)  L.pop(index) -> item -- remove and return item at index (default last)

          pop(index) 是按索引号来删除列表中对应的元素,并返回该元素,该函数的参数是索引号,也可以是空的,即pop(), 这时将最后一个元素删除

   (2)  L.remove(value) -> None -- remove first occurrence of value

          remove(value) 是根据参数value在列表中查找,若找到某个元素的值和参数相等,则将该元素删除,若没有找到,则抛出异常,该函数的参数不能为空,

                                     该函数没有返回值

>>> listA = ['a', 'b', 'c','d', 'e', 'c', 'b', 'a']>>> listA.pop(2)>>> print(listA)['a', 'b', 'd', 'e', 'c', 'b', 'a']>>> listA.remove('b')>>> print(listA)['a', 'd', 'e', 'c', 'b', 'a']

     使用 del 也可以删除列表中的元素

>>> listA=['a', 'd', 'e', 'c', 'b', 'a']>>> del listA[0]   #按索引号来删除某个元素>>> print(listA)['d', 'e', 'c', 'b', 'a']>>> del listA[1:3] #按分片来删除某些元素>>> print(listA)['d', 'b', 'a']>>> del listA      #删除整个列表print(listA)---------------------------------------------------------------------------NameError                                 Traceback (most recent call last)<ipython-input-25-3d069e557e1e> in <module>()      5 print(listA)      6 del listA----> 7 print(listA)      8       9 NameError: name 'listA' is not defined