python入门到放弃(五)-基本数据类型之list列表

2020-03-20 21:08:27 浏览数 (1)

1.概述

代码语言:javascript复制
列表是python的基本数据类型之一,是一个可变的数据类型,用[]方括号表示,每一项元素使用逗号隔开,可以装大量的数据

#先来看看list列表的源码写了什么,方法:按ctrl 鼠标左键点list

代码语言:javascript复制
class list(object):
    """
    list() -> new empty list
    list(iterable) -> new list initialized from iterable's items
    """
    def append(self, p_object): # real signature unknown; restored from __doc__
        """ L.append(object) -- append object to end """
        pass

    def count(self, value): # real signature unknown; restored from __doc__
        """ L.count(value) -> integer -- return number of occurrences of value """
        return 0

    def extend(self, iterable): # real signature unknown; restored from __doc__
        """ L.extend(iterable) -- extend list by appending elements from the iterable """
        pass

    def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
        """
        L.index(value, [start, [stop]]) -> integer -- return first index of value.
        Raises ValueError if the value is not present.
        """
        return 0

    def insert(self, index, p_object): # real signature unknown; restored from __doc__
        """ L.insert(index, object) -- insert object before index """
        pass

    def pop(self, index=None): # real signature unknown; restored from __doc__
        """
        L.pop([index]) -> item -- remove and return item at index (default last).
        Raises IndexError if list is empty or index is out of range.
        """
        pass

    def remove(self, value): # real signature unknown; restored from __doc__
        """
        L.remove(value) -- remove first occurrence of value.
        Raises ValueError if the value is not present.
        """
        pass

    def reverse(self): # real signature unknown; restored from __doc__
        """ L.reverse() -- reverse *IN PLACE* """
        pass

    def sort(self, cmp=None, key=None, reverse=False): # real signature unknown; restored from __doc__
        """
        L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
        cmp(x, y) -> -1, 0, 1
        """
        pass

    def __add__(self, y): # real signature unknown; restored from __doc__
        """ x.__add__(y) <==> x y """
        pass

    def __contains__(self, y): # real signature unknown; restored from __doc__
        """ x.__contains__(y) <==> y in x """
        pass

    def __delitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__delitem__(y) <==> del x[y] """
        pass

    def __delslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__delslice__(i, j) <==> del x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __eq__(self, y): # real signature unknown; restored from __doc__
        """ x.__eq__(y) <==> x==y """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__('name') <==> x.name """
        pass

    def __getitem__(self, y): # real signature unknown; restored from __doc__
        """ x.__getitem__(y) <==> x[y] """
        pass

    def __getslice__(self, i, j): # real signature unknown; restored from __doc__
        """
        x.__getslice__(i, j) <==> x[i:j]
                   
                   Use of negative indices is not supported.
        """
        pass

    def __ge__(self, y): # real signature unknown; restored from __doc__
        """ x.__ge__(y) <==> x>=y """
        pass

    def __gt__(self, y): # real signature unknown; restored from __doc__
        """ x.__gt__(y) <==> x>y """
        pass

    def __iadd__(self, y): # real signature unknown; restored from __doc__
        """ x.__iadd__(y) <==> x =y """
        pass

    def __imul__(self, y): # real signature unknown; restored from __doc__
        """ x.__imul__(y) <==> x*=y """
        pass

    def __init__(self, seq=()): # known special case of list.__init__
        """
        list() -> new empty list
        list(iterable) -> new list initialized from iterable's items
        # (copied from class doc)
        """
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    def __len__(self): # real signature unknown; restored from __doc__
        """ x.__len__() <==> len(x) """
        pass

    def __le__(self, y): # real signature unknown; restored from __doc__
        """ x.__le__(y) <==> x<=y """
        pass

    def __lt__(self, y): # real signature unknown; restored from __doc__
        """ x.__lt__(y) <==> x<y """
        pass

    def __mul__(self, n): # real signature unknown; restored from __doc__
        """ x.__mul__(n) <==> x*n """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __ne__(self, y): # real signature unknown; restored from __doc__
        """ x.__ne__(y) <==> x!=y """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __reversed__(self): # real signature unknown; restored from __doc__
        """ L.__reversed__() -- return a reverse iterator over the list """
        pass

    def __rmul__(self, n): # real signature unknown; restored from __doc__
        """ x.__rmul__(n) <==> n*x """
        pass

    def __setitem__(self, i, y): # real signature unknown; restored from __doc__
        """ x.__setitem__(i, y) <==> x[i]=y """
        pass

    def __setslice__(self, i, j, y): # real signature unknown; restored from __doc__
        """
        x.__setslice__(i, j, y) <==> x[i:j]=y
                   
                   Use  of negative indices is not supported.
        """
        pass

    def __sizeof__(self): # real signature unknown; restored from __doc__
        """ L.__sizeof__() -- size of L in memory, in bytes """
        pass

    __hash__ = None

list

2.列表的索引和切片

#列表和字符串一样拥有索引和切片

#索引:下标从0开始

代码语言:javascript复制
lst = ["赵四","刘能","谢大脚","谢腾飞","小蒙"]
print(lst[0]) #获取第一个元素
#赵四
print(lst[1])
#刘能
print(lst[2])
#谢大脚

print(lst[3][2])   #飞
#索引下标从0开始,3就是谢腾飞,2就是在谢腾飞中切012,就是飞

print(lst[-2]) #负就是从后面切,从-1开始,-2就是谢腾飞

#切片

代码语言:javascript复制
lst = ["赵四","刘能","谢大脚","谢腾飞","小蒙"]
print(lst[1:4]) #['刘能','谢大脚','谢腾飞']
#列表和字符串一样,顾头不顾尾,不能切到4print(lst[-3:-1]) #['谢大脚', '谢腾飞'],顾头不顾尾所以不能切到小蒙print(lst[1::2])  #['刘能', '谢腾飞']
#从1开始到结束,每隔2个输出一个print(lst[-1:-5:-2]) #['小蒙', '谢大脚']
#-1到-5,但是顾头不顾尾就不能切到-5,-2就是从右往前切,每隔2个输出一个

3.列表的增删改查

代码语言:javascript复制
#注意点:列表和str是不一样的,list可以发生改变,所以直接就在原来的对象上进行了操作
代码语言:javascript复制
#例如:
lst = ["蒋小鱼","张冲","鲁炎","展大鹏"]
lst.append("阿甘")
print(lst) #['蒋小鱼', '张冲', '鲁炎', '展大鹏', '阿甘']

#3.1增加

代码语言:javascript复制
#关键字
#append() 在后面追加
#insert() 指定位置添加
#extend() 迭代添加,也就是一个一个添加

#例子:

代码语言:javascript复制
lst = ["蒋小鱼","张冲","鲁炎","展大鹏"]
lst.append("阿甘")
print(lst) #['蒋小鱼', '张冲', '鲁炎', '展大鹏', '阿甘']

lst.insert(2,"项羽")  #在鲁炎的位置插入项羽,之前的元素相应的往后移
print(lst) #['蒋小鱼', '张冲', '项羽', '鲁炎', '展大鹏', '阿甘']

#如果使用字符串添加的话那么就是迭代一个一个添加
lst.extend("巴朗")  #['蒋小鱼', '张冲', '鲁炎', '展大鹏', '巴', '朗']

#如果使用列表方式添加,那么就是一个元素
lst.extend(["巴朗"]) #['蒋小鱼', '张冲', '鲁炎', '展大鹏', '巴朗']
print(lst)

#应用:交互输入员工信息,然后按Q退出,再打印输入的信息出来
# lst=[]
# while 1:
#     content = input("请输入员工的信息,输入Q退出:")
#     if content.upper() == 'Q':
#         break
#     lst.append(content)
# print(lst)

#3.2.删除

代码语言:javascript复制
#pop()  #指定位置删除
#remove() #删除元素
#clear()  #清空列表
#del()  #切片删除

#例子:

代码语言:javascript复制
lst = ["蒋小鱼","张冲","鲁炎","展大鹏"]
lst.pop()   #不指定位置,默认删除最后一个
print(lst) #['蒋小鱼', '张冲', '鲁炎']

el = lst.pop(2)  #删除2号元素
print(el)  #可以查看有没有删除
#鲁炎
print(lst) #再返回列表查看有没有删了
# ['蒋小鱼', '张冲', '展大鹏']

lst.remove("张冲") #指定删除的元素
print(lst) #['蒋小鱼', '鲁炎', '展大鹏']

lst.remove("张三") #如果删除不存在的元素就会报错
print(lst) #报错

lst.clear()  #清空
print(lst)

del lst[1:3] #切片删除,因为顾头不顾尾所以删除1和2
print(lst) #['蒋小鱼', '展大鹏']

#3.3.修改

代码语言:javascript复制
# 1、索引修改
# 2、切片修改

#例子:

代码语言:javascript复制
lst = ["蒋小鱼","张冲","鲁炎","展大鹏","黑脸"]
lst[1] = "乌云"  #将1号元素修改成乌云,也就是张冲改成乌云
print(lst) #['蒋小鱼', '乌云', '鲁炎', '展大鹏']

#切片:要注意后面的步长和元素的个数如果不对应的话就会报错
lst[1:4:3] = ["龙大队"] 
print(lst) #['蒋小鱼', '龙大队', '鲁炎', '展大鹏', '黑脸']

# lst[1:4:3] = ["龙大队","张三"]
#这样就会报错,因为步长是3,上面只能切到一个,但是修改了两个,不对应,所以就会报错
# print(lst)

lst[1:4] = ["大佬"] #将下标1-3替换成大佬
#如果切片没有步长或者步长是1,则不用关心个数
print(lst)  #['蒋小鱼', '大佬', '黑脸']

#3.4.查询

代码语言:javascript复制
#列表是一个可迭代对象,所以可以进行for循环
 lst = ["张三","李四","王五","李六"]
 for el in lst:
     print(el)

4.列表的嵌套

代码语言:javascript复制
#嵌套就是一层套着一层,列表套着列表
#采用降维操作,一层一层的看,
#就像洋葱一样,一层一层的拨开你的心

#例子:

代码语言:javascript复制
lst = [1,"张三","蒋小鱼",["鲁炎","张冲",3,["黑脸","龙大队","xiaotian",4],],"乌云"]

#找到张冲
print(lst[3][1]) #张冲
#是按照从下标0开始找,3首先是找到第二个列表,然后再在第二个列表里面找到1张冲

#找到黑脸和龙大队
print(lst[3][3][0:2]) #['黑脸', '龙大队']
#也是按照一层一层的找,记住是顾头不顾尾的

#将xiaotian拿到,然后首字母大写,再扔回去
s = lst[3][3][2]
s = s.capitalize()
lst[3][3][2] = s
print(lst) #[1, '张三', '蒋小鱼', ['鲁炎', '张冲', 3, ['黑脸', '龙大队', 'Xiaotian', 4]], '乌云']

#简写
# lst[3][3][2] = lst[3][3][2].capitalize()
# print(lst)

#将蒋小鱼替换成参谋长
s = lst[2]
s = s.replace("蒋小鱼","参谋长")
lst[2] = s
print(lst) #[1, '张三', '参谋长', ['鲁炎', '张冲', 3, ['黑脸', '龙大队', 'Xiaotian', 4]], '乌云']

#简写
# lst[2] = lst[2].replace("蒋小鱼","参谋长")
# print(lst)

5.列表的相关操作

代码语言:javascript复制
#count() #查询出现的次数
#sort()  #排序,默认升序
#len()   #列表的长度

#例子:

代码语言:javascript复制
lst = ["蒋小鱼","张冲","鲁炎","展大鹏","黑脸","蒋小鱼"]
c = lst.count("蒋小鱼")  #查询蒋小鱼出现的次数
print(c) #2

lst.reverse()  #反向打印
print(lst) #['蒋小鱼', '黑脸', '展大鹏', '鲁炎', '张冲', '蒋小鱼']

l = len(lst)  #计算列表的长度
print(l) #6

#排序,默认升序
lst = [1,2,3,44,11]  
lst.sort()
print(lst) #[1, 2, 3, 11, 44]

#降序
lst = [1,2,3,44,11] 
lst.sort(reverse=True) 
print(lst) #[44, 11, 3, 2, 1]

#循环删除的坑点

代码语言:javascript复制
######循环删除列表中的每一个元素(有坑)####
#方法:1.可以使用clear()清空,
#       2.使用另外一种方法,循环删

#首先来个坑,删不掉的
lst = [11,22,33,44,55]
for e in lst:
    lst.remove(e)
print(lst) #[22, 44]
#直接使用remove是删除不了的,因为删除的时候内部的索引在改变
# 当index=0的时候删除0的字符,当index=1的时候就向下移动了一位,但是列表里面的元素已经往前移填充了
#  所以当删除11,22就变成了第0个索引,当下次删除的时候就是删除第一个索引33,然后就漏掉了22,后面同样


#方法
#1.首先需要记录删除的东西
#2.然后循环要删除的列表,删除真正的列表

#例子:删除性张的
lst = ["张冲","张国荣","张曼玉","蒋小鱼"]
zhangs = [] #首先记录性张
for el in lst:
    zhangs.append(el) #将之前的列表追加到zhangs里面
for e in zhangs:
    lst.remove(e) #再删除原列表
print(lst)  #[]
print(zhangs) #['张冲', '张国荣', '张曼玉', '蒋小鱼']

0 人点赞