该整理来源于:https://www.runoob.com/python3/python3-data-structure.html

列表

python中列表是可变的,这是它区别于字符串和元组的最重要的特点了:

列表可被修改,字符串和元组不行????????

以下介绍列表的一些常用方法

 1 list = [5,2,4,3,1,6]
 2 list.append(7)  #把一个元素添加到列表的结尾
 3 print(list)
 4 list.extend([8]) #通过添加指定列表的所有元素来扩充列表
 5 print(list)
 6 list.insert(1,0) #list.insert(i,x)通过在指定的位置加入新的元素,i是准备插入到那个元素的索引
 7 print(list)
 8 list.remove(0)  #删除列表中为0的元素,若没有这个元素,则会报ValueError: list.remove(x): x not in list
 9 print(list)    
10 list.pop(6) #从列表的指定的位置移除元素,并将其返回,没有指定,就返回最后一个元素
11 print(list)
12 list.pop()
13 print(list)
14 list.index(1) #返回列表中第一个值为1的元素的索引,没有匹配则会ValueError: 0 is not in list
15 print(list)
16 list.sort() #排序
17 print(list)
18 list.reverse() #倒排列表中的元素
19 print(list)
20 list.copy()  #返回列表中的潜复制,等于a[:]
21 print(list) 
22 list.clear()  #清空列表
23 print(list)
 1 [5, 2, 4, 3, 1, 6, 7]
 2 [5, 2, 4, 3, 1, 6, 7, 8]
 3 [5, 0, 2, 4, 3, 1, 6, 7, 8]
 4 [5, 2, 4, 3, 1, 6, 7, 8]
 5 [5, 2, 4, 3, 1, 6, 8]
 6 [5, 2, 4, 3, 1, 6]
 7 [5, 2, 4, 3, 1, 6]
 8 [1, 2, 3, 4, 5, 6]
 9 [6, 5, 4, 3, 2, 1]
10 [6, 5, 4, 3, 2, 1]
11 []
View Code

相关文章:

  • 2022-02-12
  • 2022-12-23
  • 2021-06-25
  • 2021-07-24
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2018-10-31
  • 2022-12-23
  • 2022-02-03
  • 2021-06-28
  • 2022-01-29
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案