python中列表的基础知识与常用方法

列表

列表是一种存储大量数据的存储模型。具有索引的概念,可以通过索引操作列表中的数据。列表中的数据可以进行添加、删除、修改、查询等操作。

    创建一个列表:
    list1 = [1, 2, 3, 'world', 'python', True, None]
    print(list1[3])    >>> world   # 获取列表中指定索引的数据   
    list1[3] = "hello"             # 修改列表中指定索引的数据
    print(list1[3])    >>> hello
    使用for循环查看列表中的每一个数据
    for data in list1:
        print(data)
    案例:创建一个列表,包含5个整数,使用for循环完成对列表中所有数据的求和
    list2 = [1, 2, 3, 4, 5]
    sum_list2 = 0
    for i in list2:
        sum_list2 += i
    
    print(sum_list2)
    案例:创建一个列表对象,包含数据110,使用for循环遍历列表,求所有数据的平方和
    list3 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    sum_list3 = 0
    for i in list3:
        sum_list3 += i ** 2
    
    print(sum_list3)

列表的常用方法

    append(data)        在列表的末尾添加数据
    list1 = [1, 2, 3]
    list1.append("hello")
    print(list1)    >>> [1, 2, 3, 'hello']
    insert(idx, data)   在列表的指定位置插入数据 
    list1.insert(0, "你好")
    print(list1)    >>> ['你好', 1, 2, 3, 'hello']
    extend(model)       在列表的末尾添加参数对象中的所有数据
    list1 = [1, 2, 3]
    list2 = [4, 5, 6]
    list1.extend(list2)
    print(list1)    >>> [1, 2, 3, 4, 5, 6]
    remove(data)        从列表中删除指定的数据,如果数据不存在将报错
    list1 = [1, 2, 3, 'hello', 'python', True, None]
    list1.remove("hello")     
    print(list1)    >>> [1, 2, 3, 'python', True, None]
    pop(idx)            从列表中获取并删除指定索引位置上的数据
    list1 = [1, 2, 3, 'hello', 'python', True, None]
    data = list1.pop(4)
    print(data)     >>> python
    print(list1)    >>> [1, 2, 3, 'hello', True, None]
    clear()             清空列表中的数据
    list1 = [1, 2, 3, 'hello', 'python', True, None]
    list1.clear()
    print(list1)    >>> []
    index(data)         查询列表中指定数据第一次出现索引
    list1 = [1, 2, 3, 'hello', 'python', 'world', 'python']
    idx = list1.index('python')
    print(idx)      >>> 4
    count(data)         统计列表中指定数据出现的次数
    list1 = [1, 2, 3, 'hello', 'python', 'world', 'python']
    num = list1.count('python')
    print(num)      >>> 2
    批量的更改列表内的数据内容
    list1 = [1, 2, 3, 'hello', 'python', 'world', 'python']
    list1[0:3] = [4, 5, 6]
    print(list1)    >>> [4, 5, 6, 'hello', 'python', 'world', 'python']
    sort()              用于在原位置对列表进行排序
    list1 = [1, 5, 2, 3, 4]
    list1.sort()
    print(list1)    >>> [1, 2, 3, 4, 5]
    reverse()           将列表中的元素反向存放
    list1 = [1, 2, 3, 4, 5]
    list1.reverse()
    print(list1)    >>> [5, 4, 3, 2, 1]
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值