python基礎(列表中內置的函數)

append()

append追加,在列表的最後面追加元素


b=['h','e','l','l','o']
b.append('p')
print(b)#['h', 'e', 'l', 'l', 'o', 'p']

extend()

如果想要加入另一個列表,就會使用該方法

b=['h','e','l','l','o']
a=list('HELLO')
b.extend(a)
print(b)#['h', 'e', 'l', 'l', 'o', 'H', 'E', 'L', 'L', 'O']

pop()

b=['h','e','l','l','o']
b.pop()
print(b)#['h', 'e', 'l', 'l']

默認刪除最後一個元素
也可以指定元素下標進行刪除


b=['h','e','l','l','o']
b.pop(2)
print(b)#[['h', 'e', 'l', 'o']

remove()

remove方法只需要指定需要刪除的元素即可,不需要找下表,並且如果列表中右多個與要刪除的元素相同,只刪除第一個與要刪除的元素一直的元素

b=['h','e','l','l','o']
b.remove('l')
print(b)#[['h', 'e', 'l', 'o']

insert()

該方法是對列表進行插入,可以指定在某個位置進行插入,需要指定兩個參數,第一個爲插入的位置,第二個爲插入的元素.

b=['h','e','l','l','o']
b.insert(0,'p')
print(b)#['p', 'h', 'e', 'l', 'l', 'o']

count()


b=['h','e','l','l','o']
print(b.count('l'))#2

index()

如果查不到元素,就會報錯

b=['h','e','l','l','o']
print(b.index('e'))#1
print(b.index('e',2,4))#ValueError: 'e' is not in list

reverse()

該方法可反轉列表

b=['h','e','l','l','o']
b.reverse()
print(b)#['o', 'l', 'l', 'e', 'h']

sort()

list.sort(key=None,reverse=False)
該方法對於列表進行排序,如果指定key則按照指定方法進行排序,reverse設置爲True則進行逆序排


b=['h','e','l','l','o']
b.sort()
print(b)#['e', 'h', 'l', 'l', 'o']

實例:

在寫代碼的時候,我發現了raw_input在運行的時候會報錯,說沒有定義
於是我查資料看見raw_input在python2中在有,python3中raw_input與input一樣

棧的演示
songn=[]
#add the song name
while(1):
    newsong=input('Enter the name of song(if end,end -1):')
    if(newsong=="-1"):
        break
    else:
        songn.append(newsong)
# only keep five songs
while(len(songn)>5):
    songn.pop()
print(songn)
隊列的演示
itemname=[]
import time
# add the interview  name
while(1):
    newname=input('Enter the name of the interview:')
    if(newname=='end'):
        break;
    else:
        itemname.append(newname)
#in front of the people to interview list
while(len(itemname)>0):
    name=itemname.pop(0)
    print(name,'take the interview')
    time.sleep(5)# wait for 5 seconds

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章