美文网首页
(三)列表<2>方法

(三)列表<2>方法

作者: 费云帆 | 来源:发表于2018-12-18 15:36 被阅读0次

1.extend():拓展列表

>>> list1=[1,2,3]
>>> list2=[4,5,6]
>>> list1.extend(list2)
>>> list1 #原先的对象会发生变化
[1, 2, 3, 4, 5, 6]
>>> list1=[1,2,3]
>>> list3=list1+list2
>>> list3 #这是另一个对象
[1, 2, 3, 4, 5, 6]
  • extend传入的必须是可迭代的对象,比如传入一个int,就报错啦
>>> list1=[1,2,3]
>>> list2="abc"
>>> list1.extend(list2)
>>> list1
[1, 2, 3, 'a', 'b', 'c']
>>> c=4
>>> list1.extend(4)
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    list1.extend(4)
TypeError: 'int' object is not iterable
  • 更进一步的理解:
>>> list1=[1,2,3]
>>> list2=["Python",'C++','JS']
>>> id(list1)
50643912
>>> id(list2)
5257544
>>> list2.extend(list1)
>>> list2
['Python', 'C++', 'JS', 1, 2, 3]
>>> id(list2)
5257544 #貌似生成新的list2对象,内容拓展了,"窝"还是原来的"窝"

2.可迭代的对象判断---hasattr()

>>> string="python"
>>> hasattr(string,'__iter__')
True
>>> string=[1,2]
>>> hasattr(string,'__iter__')
True
>>> hasattr(3,'__iter__')
False

可以看出,hasattr()是判断对象是否含有"iter"
3.append---另一种拓展列表的函数,都是拓展列表,还是有区别的:

>>> list1=["I","like",'Python']
>>> list2=[1,2,3]
>>> list1.extend(list2)
>>> list1
['I', 'like', 'Python', 1, 2, 3] #list2列表元素在list1不再是列表
>>> list1=["I","like",'Python']
>>> list1.append(list2)
>>> list1
['I', 'like', 'Python', [1, 2, 3]]
>>> list1=["I","like",'Python']
>>> id(list1)
51046856
>>> list1.append(list2)
>>> list1
['I', 'like', 'Python', [1, 2, 3]] #list2依然是列表
>>> id(list1) #可以看到,与extend一样,虽然扩容了,但是"窝"没变
51046856
  • extend和append共同点:都能原地扩容列表,对于"原地修改"的理解:
    "原地修改"--->没有返回值--->不能赋值给变量
    append可以理解为"整体(元素还是整体)",extend可以理解为"局部(元素被拆分)"
    扩容后,它们的列表长度是不一样的,这个也要注意下...
>>> list1=[1,2,3]
>>> example=list1.extend([4,5,6])
>>> example #这里啥也没有
>>> print(example) #返回None,即什么都没有
None

4.count()---统计列表元素出现的次数

>>> list1=[1,2,3,1,1,5,6,6,6]
>>> list1.count(1)
3
>>> list1.count(6)
3
>>> list1.count(7) #没有这个元素,不会报错,返回0次
0
>>> 

5.insert(i,x)---向列表的任意位置插入元素(extend和append是向列表末尾追加元素),insert()也是没有返回值,或者返回值为None.

>>> list1=[1,2,3,4]
>>> list1.insert(0,1234) #索引0的位置插入1234
>>> list1
[1234, 1, 2, 3, 4]
  • 这两种方法是等同的:
>>> list1.insert(len(list1),5)
>>> list1
[1234, 1, 2, 3, 4, 5]
>>> list1=[1234, 1, 2, 3, 4]
>>> list1.append(5)
>>> list1
[1234, 1, 2, 3, 4, 5]

6.删除列表元素的两种方法:remove()和pop():
先看remove():

>>> help(list.remove)
Help on method_descriptor:

remove(...)
    #None表示没有返回值
    L.remove(value) -> None -- remove first occurrence of value.
    Raises ValueError if the value is not present.
  • 基础实例:
>>> list1=['a','b','c','d','e','f']
>>> list1.remove('c')
>>> list1
['a', 'b', 'd', 'e', 'f']
>>> list2=['python','go','.net','python']
>>> list2.remove('python')
>>> list2
#只会删除第一个符合条件的元素
['go', '.net', 'python']
  • 配合判断,循环,删除全部指定的元素:
list1=['python','js','.net','python']
"""if 'python' in list1:
    list1.remove('python')
    print(list1)
else:
    print('python is not in')"""
for i in list1:
    if i=='python':
        list1.remove(i)
print(list1)
>>>['js', '.net']

下面介绍pop():

>>> help(list.pop)
Help on method_descriptor:

pop(...)
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.

可以看出,传入的是一个可选索引(不同于remove传入的是值),如果不传入参数,那么默认的是删除最后一个元素,都是返回这个被删除的元素,pop()是有返回值的.

>>> list1=['a','b','c','d','e']
>>> list1.pop()
'e'
>>> type(list1.pop())
<class 'str'>
>>> list1.pop('c') #传入值会报错,因为要求的是索引
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    list1.pop('c')
TypeError: 'str' object cannot be interpreted as an integer
>>> list1.pop(2)
'c'
>>> list1 #list1变了
['a', 'b']

7.reverse():列表的顺序反过来,没有返回值,区别于内建函数reversed()
列表方法list.reverse()是对list原地修改,list原地改变,故不能再赋值
内建reversed()是有返回值的,不是原地修改,故可以赋值

>>> list1=[1,2,3,4,5,6]
>>> list1.reverse()
>>> list1
[6, 5, 4, 3, 2, 1]
>>> list2=[1,2,3,4,5]
>>> list2.reversed() #reversed()是内建函数,不是列表的方法
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    list2.reversed()
AttributeError: 'list' object has no attribute 'reversed'
>>> reversed(list2) 
<list_reverseiterator object at 0x000000000312F5F8>
>>> list(reversed(list2)) #不仅反向,并且有返回值
[5, 4, 3, 2, 1]
>>> 

8.list.sort():对列表进行排序,没有返回值

>>> help(list.sort)
Help on method_descriptor:

sort(...)
    # key表示关键字字段
    L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
  • 实例:
>>> list1=[5,9,3,6,1]
>>> list1.sort()
>>> list1
# 默认从小到大排序
[1, 3, 5, 6, 9]
>>> list1.sort(reverse=True)
>>> list1
# 从大到小
[9, 6, 5, 3, 1]
>>> list2=['']
>>> list2=['C','C++','Java','Python','.net']
# 传入关键字字段
>>> list2.sort(key=len)
>>> list2
['C', 'C++', 'Java', '.net', 'Python']
>>> 
  • 对比下内建sorted()---有返回值的:
>>> help(sorted)
Help on built-in function sorted in module builtins:

sorted(iterable, key=None, reverse=False)
    Return a new list containing all items from the iterable in ascending order.
    
    A custom key function can be supplied to customise the sort order, and the
    reverse flag can be set to request the result in descending order.

>>> list1=[5,9,3,6,1]
>>> sorted(list1)
# 直接有返回值的,list.sort()是直接修改原来的列表
[1, 3, 5, 6, 9]
>>> list2=['C','C++','Java','Python','.net']
>>> sorted(list2,key=len)
['C', 'C++', 'Java', '.net', 'Python']

补充:

  • 类似"入栈和出栈"的操作---pop()和append()
list1=['a','b','c','d','e','f','g']
list2=[]
Active=True
while Active:
    list2.append(list1.pop())
    if list1==[]:
        #一样的效果
        #break
        Active=False
print(list2) # ['g', 'f', 'e', 'd', 'c', 'b', 'a']
print(list2[::-1]) # ['a', 'b', 'c', 'd', 'e', 'f', 'g']
#list2没有发生变化
print(list2) # ['g', 'f', 'e', 'd', 'c', 'b', 'a']
  • 之前错误的模拟:
list1=['a','b','c','d','e','f','g']
list2=[]
for i in list1:
    list2.append(list1.pop())
# 'a'和'b'为什么没有?
# 因为遍历到字符'd'的时候,后面的字符已经不存在了,遍历结束了(此时是不会报错的...)
print(list2) # ['g', 'f', 'e', 'd']

相关文章

  • (三)列表<2>方法

    1.extend():拓展列表 extend传入的必须是可迭代的对象,比如传入一个int,就报错啦 更进一步的理解...

  • 列表

    创建列表 列表里可以嵌套列表 列表操作方法 列表对象.对应方法(数据) 列表添加1、+2、追加 append...

  • ios中runtime 笔记

    常见方法 1.获取属性列表 2.获取方法列表 3,获取成员变量列表 4,获取协议列表 5,获得类方法

  • 消息转发机制

    RunTime: 1、获取所有的属性列表、方法列表、协议列表 2、方法交换 3、方法拦截调用,容错处理 4、动态添...

  • Markdown 系列(三) 列表

    无序列表 由圆点组成的列表 列表1 列表2 列表3 列表1 列表2 列表3 列表1 列表2 列表3 +-*这三种符...

  • Python列表函数&方法(补充)

    列表相关的方法 1.in 和 not in 元素n in 列表2 ---> 元素n是否是列表2的元素元素n ...

  • java语言基础

    0.方法签名:方法名+参数列表 1.方法的重载(Overload):(1)、方法名相同,参数列表不同,(2)、在编...

  • ubuntun 16.04 mysql 修改密码和开放远程访问

    进入配置文件 重启mysql 无密码进入mysql命令 列表字段的三种方法:方法 1:DESC user;方法 2...

  • 3-4 如何进行反向迭代以及如何实现反向迭代

    反向迭代列表 方法1,问题:破坏原列表Paste_Image.png 方法2,问题:浪费空间Paste_Image...

  • Python100例--007

    题目:将一个列表的数据复制到另一个列表中。方法一: 方法二: 方法三: 方法四:

网友评论

      本文标题:(三)列表<2>方法

      本文链接:https://www.haomeiwen.com/subject/mfzkkqtx.html