List: denoted by []
Common methods: List.append,list.insert,list.remove,list.pop,list.count,list.sort,list.reverse,list.index,list.copy
Common operations:
list_1 = [' haha ', ' xixi ', ' lala ', ' hehe ', ' Zizi ', ' Wuwu ']
Print (List_1[1:3]) # #打印出下标为1到3 (excluding 3) elements
Print (list_1[-3:]) # #打印出最后三个元素
Print (List_1[-1]) # #打印出最后一个元素
Print (list_1[:]) # #打印出整个列表的元素
Print (list_1[::]) # #打印出整个列表的元素, step 0
Print (List_1[:2]) # #打印出下标为0到2 (excluding 2) elements
Print (List_1[::2]) # #打印出整个列表中从下标为0开始每隔2个下标的元素
List_1[0] = ' Moto ' # #将列表中第一个元素的值改为moto
List_1.append (' Hello ') # #在列表末尾追加hello这个元素
List_1.insert (1, ' Fuck ') # #在下标为1处追加一个值为fuck的元素
List_1.remove (' Fuck ') # #删除fuck这个元素
List_1.pop () # #删除列表中最后一个元素
List_1.pop (1) # #删除列表中下标为1的元素
List_1.insert (2, ' Zizi ')
Print (List_1.count (' Zizi ')) # #统计列表中zizi元素的个数
Print (List_1.index (' hehe ')) # #显示列表中hehe元素的下标
List_1.reverse () # #反转列表
List_1.sort () # #对列表排序
list_2 = [' Beijing ', ' Shanghai ', ' Guangzhou ', ' Shenzhen ']
List_1.extend (list_2) # #将list_2追加到list_1中
List_3 = List_1.copy () # #拷贝list_1到list_3
Deep copy and shallow copy differences:
Shallow copy: Copy only the first element of the list, and when the second-level list is included, only the memory address is copied and not the contents of the second-level list, so the elements of the newly generated list change when the elements in the second-level list change
Cases:
Nihao_1 = [' How ', ' is ', ' you ', [' haha ', ' xixi ']
Nihao_3 = Nihao_1.copy ()
Print (Nihao_1)
Print (Nihao_3)
NIHAO_1[2] = ' yours '
Nihao_1[3][0] = ' lala '
Print (Nihao_1)
Print (Nihao_3)
Results:
[' How ', ' is ', ' you ', [' haha ', ' xixi ']
[' How ', ' is ', ' you ', [' haha ', ' xixi ']
[' How ', ' is ', ' yours ', [' Lala ', ' Xixi ']
[' How ', ' is ', ' you ', [' Lala ', ' Xixi ']
Deep copy: Copy all elements from the list
Cases:
Nihao_1 = [' How ', ' is ', ' you ', [' haha ', ' xixi ']
Nihao_3 = Copy.deepcopy (nihao_1)
Print (Nihao_1)
Print (Nihao_3)
NIHAO_1[2] = ' yours '
Nihao_1[3][0] = ' lala '
Print (Nihao_1)
Print (Nihao_3)
Results:
[' How ', ' is ', ' you ', [' haha ', ' xixi ']
[' How ', ' is ', ' you ', [' haha ', ' xixi ']
[' How ', ' is ', ' yours ', [' Lala ', ' Xixi ']
[' How ', ' is ', ' you ', [' haha ', ' xixi ']
List of Python Basics (ii)