py03-python基础-列表
1、列表
作用:多个装逼,多个爱好,多门课程,多个女朋友等。
定义:[]内可以是是任意类型的值,逗号分隔。
例子:
my_girl_friends=['alex','wupeiqi','yuanhao','zhangsan','lisi']
#my_girl_friends=list(['alex','wupeiqi','zhangsan','lisi','wangwu'])
print(my_girl_friends)
2、列表的常用操作:
索引:
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
print(my_boy_friends[1])
切片:顾头不顾尾;打印索引下标1-3
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
print(my_boy_friends[1:3])
追加:不能追加多个
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
# print(my_boy_friends[1:3])
my_boy_friends.append('oldboy')
print(my_boy_friends)
删除:
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
my_boy_friends.pop()
print(my_boy_friends) #pop默认从后面往前面弹出
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
my_boy_friends.pop(0)
print(my_boy_friends) #pop弹出索引标识为1
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
my_boy_friends.remove('wupeiqi')
print(my_boy_friends) #remove删除的是值
长度:值的个数
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30] print(my_boy_friends.__len__())
等价于
print(len(my_boy_friends))
包含in:
print('alex' in my_boy_friends)
字符串也能包含in
msg='my name is xtyang' print('xtyang' in msg)
其他操作命令:
清空列表:
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30] my_boy_friends.clear() print(my_boy_friends)
拷贝列表:
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30] my_girl_friends=my_boy_friends.copy() print(my_girl_friends)
统计列表中值出现的次数:
my_boy_friends=['alex','wupeiqi','yuanhao','alex','wupeiqi',4,10,30] print(my_boy_friends.count('alex')) print(my_boy_friends.count('wupeiqi'))
追加多个值:
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
my_boy_friends.extend(['oldboy','oldboy01','oldboy02'])
print(my_boy_friends)
查看列表索引的下标
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
my_boy_friends.extend(['oldboy','oldboy01','oldboy02'])
print(my_boy_friends.index('oldboy'))
列表的翻转:整个列表倒过来
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30]
my_boy_friends.extend(['oldboy','oldboy01','oldboy02'])
print(my_boy_friends)
my_boy_friends.reverse()
print(my_boy_friends)
列表排序:从小到大
l=[10,-1,28,3,2,9] l.sort() print(l)
排序后再翻转,从大到小
l=[10,-1,28,3,2,9] l.sort(reverse=True) print(l)
插入:插入指定的位置
my_boy_friends=['alex','wupeiqi','yuanhao',4,10,30] my_boy_friends.insert(1,'sb') print(my_boy_friends)
2、队列和堆栈的区别
队列:先进先出
lifo=[] lifo.append(1) lifo.append(2) lifo.append(3) print(lifo) print(lifo.pop(0)) print(lifo.pop(0)) print(lifo.pop(0))
或者
lifo=[]
lifo.insert(0,1)
lifo.insert(0,2)
lifo.insert(0,3)
print(lifo)
print(lifo.pop())
print(lifo.pop())
print(lifo.pop())
堆栈:先进后出
fifo=[] fifo.append(1) fifo.append(2) fifo.append(3) print(fifo) print(fifo.pop()) print(fifo.pop()) print(fifo.pop())
或者
fifo=[]
fifo.insert(0,1)
fifo.insert(0,2)
fifo.insert(0,3)
print(fifo)
print(fifo.pop(0))
print(fifo.pop(0))
print(fifo.pop(0))
3、列表练习
data=['sysgit',18,[1990,9,1]]
print(data[0])
print(data[1])
print(data[2])
name,age,birth=['sysgit',18,[1990,9,1]]
print(name)
print(age)
print(birth)
字符串也是一一对应关系
a,b,c,d,e='hello' print(a,b,c,d,e)
www.sysgit.com