python切片復(fù)制列表的知識點(diǎn)詳解
1、不指定開始和結(jié)束的索引[:],這樣得到的切片就可以包含整個列表,然后給切片一個新的變量,從而實(shí)現(xiàn)復(fù)制列表。
2、創(chuàng)建原始列表的副本,兩個列表的操作不會影響。
實(shí)例
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學(xué)習(xí)筆記之列表切片代碼示例
"""切片"""
pepole = ["koulong","liding","ceshi","xiaohong"]
print(pepole[0:1])
print(pepole[:2])
print(pepole[-1:])
#訪問所有元素的切片
for people in pepole[0:1]:
print(people.title())
#復(fù)制切片
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]))
到此這篇關(guān)于python切片復(fù)制列表的知識點(diǎn)詳解的文章就介紹到這了,更多相關(guān)python切片復(fù)制列表的本質(zhì)內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。
關(guān)注官方微信