-*-列表是新手可直接使用的最強大的python功能之一,它融合了眾多重要的編程概念。-*-
# -*- coding:utf-8 -*-
# Author:sweeping-monk
Question_1 = "什么是列表?"
print(Question_1)
smg = "列表由一系列按特定順序排列的元素組成。你可以創建包含所有字母,數字0—9或者所有小組成員的列表,也可以將任何東西加入列表,其中元素之間沒有任何關系。"
print(smg)
Method_1 = "在python中,用([])來表示列表,用逗號來分隔其中的元素。下面用一個簡單的例子來說明"
print(Method_1)
name = ['zhangsan','lisi','wangwu','678','張揚']
print(name)
Question_2 = "如何訪問列表元素?"
print(Question_2)
smg2 = '''
列表是有序集合,要訪問列表任何元素,只需將該元素的位置和索引告訴python就可以;在python中,第一個列表元素的索引為0,而不是1。
python為訪問最后一個列表元素提供了特殊的語法,通過將索引指定為-1,可讓python返回最后一個列表元素,這中語法很有用。
'''
print(smg2)
Method_2 = "具體請看下面的程序:"
print(Method_2)
name1 = ['zhangsan','lisi','wangwu','678','張揚']
print(name1[0]) #第一個列表元素的索引為0。
print(name1[1])
print(name1[-1]) #特殊語法
print(name1[-2])
print(name1[0].title()) #加方法可以使用戶看到的結果---整潔,干凈。
message = " my name is " + name1[-3].title() + "!" #從列表中取元素拼接一句話。
print(message)
Chicken_soup = "工作中你創建的列表大多都是動態的,這意味著列表創建后,將隨著程序的運行增刪元素"
print(Chicken_soup)
Modify_list_elements = ['zhangsan','lisi','wangwu']
print(Modify_list_elements)
Modify_list_elements[0] = 'xiaole' #修改列表中第一個元素。
print(Modify_list_elements)
Add_list_elements = []
Add_list_elements.append('zhangshan') #在空列表中添加元素。
Add_list_elements.append('lisi')
Add_list_elements.append('wangwu')
print(Add_list_elements)
Add_list_elements.append('xiaole') #在列表元素末尾添加元素。
print(Add_list_elements)
Add_list_elements.insert(0,'sunyuan') #在列表第一個元素前面添加元素。
print(Add_list_elements)
Add_list_elements.insert(2,'huahua') #在列表第三個元素前面添加元素。
print(Add_list_elements)
del Add_list_elements[1] #使用del可刪除任意位置處的列表元素,條件是你必須先知道其元素所在列表中的位置(索引)。
print(Add_list_elements)
Weed_out_the_bottom = ['sunyuan','xiaole','jitao','huahua']
print(Weed_out_the_bottom)
popped_the_bottom = Weed_out_the_bottom.pop() #方法pop(),pop(術語彈出)可刪除列表末尾的元素,并讓你能夠接著使用被刪除的元素值。
print(Weed_out_the_bottom) #在列表中顯示是否剔除了末位。
print(popped_the_bottom) #把末位被剔除的誰給打印出來
Chicken_soup_1 = "列表就像一個棧,而刪除列表末尾的元素就相當于彈出棧頂的元素。"
print(Chicken_soup_1)
popup = ['zhansan','lisi','wangwu','xiaole']
print(popup)
popup_1 = popup.pop(1) #彈出列表中任意位置的元素,這里彈出列表中第二位置的元素。
print(popup)
print(popup_1)
popup_2 = popup.pop(0) #彈出列表中任意位置的元素,這里彈出列表中第一位置的元素。
print(popup)
print(popup_2)
Chicken_soup_2 = "凡事要舉一反三多緯度思考,前面我們是根據元素位置信息來刪除元素,反之也可以根據元素值來刪除元素。"
The_delete = ['zhangsan','lisi','wangwu','xiaole']
print(The_delete)
The_delete.remove('wangwu') #不知道元素位置,但知道位置值可以用這種方法刪除。
print(The_delete)
The_delete_1 = ['zhangsan','lisi','wangwu','xiaole']
print(The_delete_1)
my_favorite_person = "xiaole" #使用remove()從列表中刪除元素時,也可以接著使用它的值。
The_delete_1.remove(my_favorite_person)
print(The_delete_1)
print("\n" + my_favorite_person.title() + " " "is my favorite person.")
Chicken_soup_3 = "方法remove()只刪除第一個指定的值;如果要刪除的值可能在列表中多次出現,就需要使用while循環來判斷是否刪除了所有這樣的值。"
pets = ['dog','cat','dog','goldfish','cat','rabbit','cat']
print(pets)
while 'cat' in pets: #使用while in 循環來逐個刪除多個'cat'。
pets.remove('cat')
print(pets)