编程语言
首页 > 编程语言> > python列表所有的增、删、改、查、及其他操作操作

python列表所有的增、删、改、查、及其他操作操作

作者:互联网

 

增(2)

 

  1. .append(元素)

    1 list=['csgo',100,'pacify','cs1.6','unturned']
    2 list.append('RainbowSix')
    3 print(list)
    4 
    5 #['csgo', 100, 'pacify', 'cs1.6', 'unturned', 'RainbowSix']
    6 
    7 #进程已结束,退出代码0
    直接在列表最后增加

     

  2. .insert(位置,元素)

     1 list=['csgo',100,'pacify','cs1.6','unturned']
     2 list.append('RainbowSix')
     3 list.insert(-1,'hell let loose')
     4 list.insert(0,'project winter')
     5 print(list)
     6 
     7 
     8 #['project winter', 'csgo', 100, 'pacify', 'cs1.6', 'unturned', 'hell let #loose', 'RainbowSix']
     9 
    10 #进程已结束,退出代码0
    在指定位置左边添加元素

 

 

 

   PS append比insert好,因为insert会移动其它元素,没有append快

删(4)

  1. .remove(元素)

    1 list=['csgo',100,'pacify','cs1.6','unturned']
    2 list.remove('csgo')
    3 print(list)
    4 
    5 
    6 
    7 #[100, 'pacify', 'cs1.6', 'unturned']
    8 
    9 #进程已结束,退出代码0
    删指定元素

    若有多个同名元素,则只能删去第一个

     

  2. .pop()

     1 list=['csgo',100,'pacify','cs1.6','unturned']
     2 list.pop()
     3 print(list)      #['csgo', 100, 'pacify', 'cs1.6']
     4 
     5 
     6 
     7 list=['csgo',100,'pacify','cs1.6','unturned']
     8 list.pop(0)
     9 print(list)      #[100, 'pacify', 'cs1.6', 'unturned']
    10 
    11 
    12 
    13 
    14 list=['csgo',100,'pacify','cs1.6','unturned']
    15 a=list.pop(0)
    16 print(a)         #csgo
    默认删除列表最后的元素,也可以指定位置,同时也有返回值,返回删掉的元素

     

  3. del list[索引]

    1 list=['csgo',100,'pacify','cs1.6','unturned']
    2 del list[0]
    3 print(list)     #[100, 'pacify', 'cs1.6', 'unturned'
    用python关键字del删除

     

  4. .clear()  直接删除整个列表内所有元素

改(1)

  list[位置]=值。直接索引到一个位置的元素

查(1)

  1.   list[位置]
 1 list=['csgo',100,'pacify','cs1.6','unturned']
 2 for i in range(len(list)):
 3     print(i)
 4     print(list[i])
 5 
 6 
 7 #0
 8 #csgo
 9 #1
10 #100
11 #2
12 #pacify
13 #3
14 #cs1.6
15 #4
16 #unturned
17 
18 #进程已结束,退出代码0
查列表所有元素及对应索引

其他(4)

  1. .reverse()   

    1 list=['csgo',100,'pacify','cs1.6','unturned']
    2 print(list)        #['csgo', 100, 'pacify', 'cs1.6', 'unturned']
    3 list.reverse()
    4 print(list)         #['unturned', 'cs1.6', 'pacify', 100, 'csgo']
    5 
    6 
    7 
    8 
    9 进程已结束,退出代码0
    翻转,逆置列表

     

  2. .count(元素)  

    1 list=['csgo',100,'pacify','cs1.6','unturned']
    2 a=list.count('csgo')
    3 print(a)     #1
    查找列表中某元素的个数

     

  3. .sort()  排序

    1 list=[999,888,899,123456,1231]
    2 list.sort()
    3 print(list)                    #[888, 899, 999, 1231, 123456]
    4 list.sort(reverse=True) 
    5 print(list)                    #[123456, 1231, 999, 899, 888]
    6  
    默认从小到大排 要从大到小就传参数 reverse=True 。PS:字母也可以排序

     

  4. len(list),调用python内置函数len()求列表的长度。

    列表在类的定义中有__len__内置方法,len()的返回值就是该方法的返回值,返回列表元素的个数

     

     

 

 

标签:python,cs1.6,unturned,list,列表,csgo,pacify,操作,100
来源: https://www.cnblogs.com/heike195929/p/14717451.html