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

发布了79 篇原创文章 · 获赞 55 · 访问量 7176

猜你喜欢

转载自blog.csdn.net/qq_45353823/article/details/104342196