设为首页收藏本站
查看: 45|回复: 0

[PHP] python基础-list

[复制链接]

论坛元老

Rank: 6Rank: 6

积分
34274
主题
17031
UID
1347
M币
67
贡献
17176

  • 发表于 2017-5-14 02:44:00 | 显示全部楼层 |阅读模式
    1、list创建
    new_list1 = ['TV','Car','Cloth','Food']
    new_list2 = list(['TV','Car','Cloth','Food'])
    print (new_list1)
    print (new_list2)
    运行结果:
    ['TV', 'Car', 'Cloth', 'Food']
    ['TV', 'Car', 'Cloth', 'Food']
    2、list常用的方法:
    1. append
    new_list1 = ['TV','Car','Cloth','Food']
    print (new_list1)
    new_list1.append('Water') #追加'water'
    print (new_list1)
    运行结果:
    ['TV', 'Car', 'Cloth', 'Food']
    ['TV', 'Car', 'Cloth', 'Food', 'Water']
    2.count
    new_list1 = ['TV','Car','Cloth','Food','Food']
    print (new_list1.count('Food')) #统计'food'在列表中的次数 => 2次
    3.extend
    new_list1 = ['TV','Car','Cloth','Food','Food']
    new_list1.extend([11,22,33,'Car'])
    print (new_list1)
    运行结果:
    ['TV', 'Car', 'Cloth', 'Food', 'Food', 11, 22, 33, 'Car']
    4.sort
    new_list1 = ['TV','Car','Cloth','Food','Food']
    print (new_list1)
    new_list1.sort() #正向排序
    print (new_list1)
    new_list1.sort(reverse=True) #反向排序
    print (new_list1)
    运行结果:
    ['TV', 'Car', 'Cloth', 'Food', 'Food']
    ['Car', 'Cloth', 'Food', 'Food', 'TV'] #正向排序结果
    ['TV', 'Food', 'Food', 'Cloth', 'Car'] #反向排序结果
    5. len
    new_list1 = ['TV','Car','Food','Cloth','Food']
    print (len(new_list1)) => 5 #打印元素的个数
    6.remove
    new_list1 = ['TV','Car','Food','Cloth','Food']
    new_list1.remove('Food')
    print (new_list1)
    运行结果:
    ['TV', 'Car', 'Cloth', 'Food'] #remove会删除找到的第一个相同元素
    7.pop
    new_list1 = ['TV','Car','Food','Cloth','Food']
    new_list1.pop() #随机删除一个元素
    print (new_list1)
    new_list1.pop(2) #指定删除某个元素
    print (new_list1)
    运行结果为:
    ['TV', 'Car', 'Food', 'Cloth']
    ['TV', 'Car', 'Cloth'] #,此处删除的是第3个元素'Food'
    8.index
    new_list1 = ['TV','Car','Food','Cloth','Food']
    print (new_list1.index('Food')) #返回指定元素的index值,相同元素返回查找到的第一个
    运行结果为:2
    9.insert
    new_list1 = ['TV','Car','Food','Cloth','Food']
    new_list1.insert(2,'HAHAHA') #向指定的位置插入元素
    print (new_list1)
    运行结果为:
    ['TV', 'Car', 'HAHAHA', 'Food', 'Cloth', 'Food']
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    在我站开通SVIP可同时获得17个站点VIP资源 立即登录 立即注册
    快速回复 返回顶部 返回列表