Python学习之路-list的常用方法

  • append()
  • insert(index,obj) #可以向指定位置添加
    1 __author__ = "KuanKuan"
    2 list = []
    3 list.append("JankinYu")
    4 list.insert(0,"kali")
    5 print(list)
    #输出结果
    #['kali', 'JankinYu']

     

 

  • pop()#可以删除指定位置如果不给参数默认删除最后一个
  • remove()#可以删除指定的一个值
  • del
  • list1 = ["JankinYu","kuankuan","梳子","卡农"]
    print(list1)
    list1.remove(
    "梳子") print(list1) list1.pop() print(list1) del list1[1] print(list1) #输出结果
    #['JankinYu', 'kuankuan', '梳子', '卡农']
    #['JankinYu', 'kuankuan', '卡农'] #['JankinYu', 'kuankuan'] #['JankinYu']

     

 

  • list[index]=value
  • list3 = ['1','2','3','4','5','6','7','8','9']
    list3[8] = 666
    print(list3)
    #输出结果
    #['1', '2', '3', '4', '5', '6', '7', '8', 666]

     

  • index()#查找值的下标
  • 切片list[start:end:step]
    list3 = ['1','2','3','4','5','6','7','8','9']
    print(list3[0:9:2])
    print("取list3里下标0-4的值:",list3[0:5])
    print(list3)
    #输出结果
    #['1', '3', '5', '7', '9']
    #取list3里下标0-4的值: ['1', '2', '3', '4', '5']
    #8

     

拷贝

    • 别名绑定:list1=list2
    • 浅拷贝4种方式 
      • names1 = names.copy() # 浅copy 相当于copy.copy()
      • names2 = copy.copy(names)
      • names3 = names[:]
      • names4 = list(names)

     深拷贝:list2=copy.deepcopy(list1)

 1 __author__ = "KuanKuan"
 2 import copy
 3 list_name=[1,2,3,4,5]
 4 name=list_name.copy()
 5 print(name)
 6 name1=copy.copy(list_name)
 7 print(name1)
 8 name2=list_name[:]
 9 print(name2)
10 name3=list(list_name)
11 print(list_name)
12 b=copy.deepcopy(list_name)
13 print(b)

其他

    • 计数:count()
    • 反转:reverse()
    • 排序:sort() # 按照ascii码表的排序规则
    • 扩展:extend()
    • 遍历:for…in…
    • 清空:clear()
posted @ 2018-02-21 11:11  Kils  阅读(137)  评论(0编辑  收藏  举报