python基础知识总结---数据结构---列表

本文详细介绍了Python中列表的基本操作,包括列表的创建、修改、统计、查找、删除及排序等常见方法。通过实例演示了如何使用append、insert、extend等方法来添加元素,以及如何利用pop和remove进行删除操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上代码:

def listAction():
    #2.0 列表
    print "将字符串转成列表",list("hello");
    exl = list("hello");
    print exl[0];  ##读取列表中item
    print ''.join(exl);  ## 将列表转成字符串

    #2.0.1 对列表的操作---添加item
    exList = [None]*10;
    #对列表添加item
    #下标赋值, add item,append,insert,extend
    print "初始化列表: ",exList

    #下标赋值--会改变列表的值
    exList[0]="test";
    print "exList items: ",exList;

    #分片add item  添加在列表项的左后位置,如果有None 将代替None
    exList[1:3] = ["fuck","james"]
    print "分片添加item 后: ",exList

    #apend add item
    ##始终是在列表的最后位置,并扩展列表的长度
    exList.append("mother")
    print "apend add item",exList

    #insert add item
    #在指定列表的位置前面插入item,会改变列表的长度
    exList.insert(3,"mother");
    print "insert add item ",exList

    #extend add items
    #在列表项的最后位置添加多个item 会改变列表的长度
    ext = ["add","del"]
    exList.extend(ext)
    print "用extend 给列表添加多个item",exList

    #2.0.2 对列表的操作---统计item 出现在列表中的次数
    #count
    print "count 统计 列表中item在list中出现的次数:", exList.count("test");

    #2.0.3 对列表的操作---查找列表中第一个匹配项的位置索引
    #index 查找列表中第一个匹配项的位置索引,如果没有匹配就会报异常
    print "查找匹配项",exList.index("james")

    #2.0.4 对列表的操作---删除
    #pop 删除列表最后的item
    exList.pop();
    print "删除后:",exList

    # remove 删除莫一项
    exList.remove("test")
    print "用remove 删除列表项后:",exList;

    #2.1 列表的排序操作
def sortTest():
    sortList = [1,4,6,3,8]
    #用sort 排序 会改变整个列表的item值
    sortList.sort();
    print "sort排序后的列表:",sortList;

    #如果用sorted 只是返回一个排序后的列表的副本,原来的列表不变
    sortList = [1,4,6,3,8]
    tem = sorted(sortList);
    print "用sorted排序后的列表:",tem;
    print "原来的列表:",sortList;

    #use reverse 去反序列表 原来的列表只会变
    sortList = [1,4,6,3,8]
    sortList.reverse()
    print "用reverse 去列表的反序排列",sortList

    #用reversed去反序列表 原来的列表不变,返回一个迭代器iterator
    #可以转换成list
    sortList = [1,4,6,3,8]
    temp = reversed(sortList)
    list(temp) #将迭代器转成list
    print "去反序后的列表:",tem;
    print "运来的列表:",sortList;

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值