1、不指定開始和結束的索引[:],這樣得到的切片就可以包含整個列表,然后給切片一個新的變量,從而實現復制列表。
2、創建原始列表的副本,兩個列表的操作不會影響。
實例
1
2
3
4
5
6
7
8
9
|
names = [ "Jerry" , "Tom" ] names_copy = names[:] names.append( "Ann" ) names_copy.append( "Bob" ) print (f "names:{names}" ) print (f "names_copy:{names_copy}" ) # output: # names:['Jerry', 'Tom', 'Ann'] # names_copy:['Jerry', 'Tom', 'Bob'] |
Python學習筆記之列表切片代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
"""切片""" pepole = [ "koulong" , "liding" , "ceshi" , "xiaohong" ] print (pepole[ 0 : 1 ]) print (pepole[: 2 ]) print (pepole[ - 1 :]) #訪問所有元素的切片 for people in pepole[ 0 : 1 ]: print (people.title()) #復制切片 my_foods = [ "香蕉" , "蘋果" , "梨子" ] my_friend_foods = my_foods[ 0 : 2 ] print ( "我最喜歡的水果:" + str (my_foods)) print ( "我最喜歡的水果分別是:" ) for my_foods1 in my_foods: print (my_foods1) print ( "我朋友最喜歡的水果:" + str (my_friend_foods)) print ( "我朋友最喜歡的水果分別是" ) for my_friend_foods1 in my_friend_foods: print (my_friend_foods1) my_friend_foods.append( "葡萄" ) print ( "我朋友最喜歡的水果:" + str (my_friend_foods)) my_friend_foods2 = my_friend_foods.remove( "葡萄" ) my_friend_foods.append( "西瓜" ) print (my_friend_foods) #動手練一練 my_foods.append( "芒果" ) print ( "我最喜歡的前2個水果:" + str (my_foods[ 0 : 2 ])) print (my_foods) print ( "我最喜歡的四個水果中的中間2個水果:" + str (my_foods[ 1 : 3 ])) print ( "我最喜歡的最后三個水果:" + str (my_foods[ 1 : 4 ])) |
到此這篇關于python切片復制列表的知識點詳解的文章就介紹到這了,更多相關python切片復制列表的本質內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://www.py.cn/jishu/jichu/33771.html