文章目录
列表
列表就像整型,字符型一样,本身就是一个数据类型。 python中的列表类似于c语言中的数组。
但是C语言中的数组只能定义的一组相同数据类型的数据。 而list就相当于高级版的数组,它可以定义不同类型的数据。 列表的表示为中括号
列表的创建
数组:存储同一种数据类型的集合 scores = [1,2,3]
列表:可以存储任意数据类型的集合
a = [1,2.2,3,True,'hello']
print(a,type(a))
结果
In [1]: name1 = 'tom'
In [2]: name2 = 'Tony'
In [3]: name3 = 'coco'
In [4]: name1
Out[4]: 'tom'
In [5]: name2
Out[5]: 'Tony'
In [6]: name3
Out[6]: 'coco'
In [7]:
In [7]: name = ['tom','Tony','coco']
In [8]:
In [8]: name
Out[8]: ['tom', 'Tony', 'coco']
In [9]: type(name)
Out[9]: list
列表的嵌套使用
列表里也可以嵌套列表(列表:本身也是一种数据类型)
li = [1,2,3,False,'python',[1,2,3,4,5]]
print(li,type(li))
结果
随机输出一个乱序的列表
import random
li = list(range(10))
# 快速生成列表
random.shuffle(li)
print(li)
结果
列表的特性
索引
service = ['http','ssh','ftp']
print(service[0])
print(service[-1])
结果
切片
service = ['http','ssh','ftp']
print(service[1:])
print(service[:-1])
print(service[::-1])
结果
重复
service = ['http','ssh','ftp']
print(service * 3)
结果
连接
service = ['http','ssh','ftp']
service1 = ['mysql','firewalld']
print(service + service1)
结果
成员操作符
service = ['http','ssh','ftp']
print('firewalld' in service)
print('ftp' in service)
结果
for循环 (迭代)
service = ['http','ssh','ftp']
for se in service:
print(se)
结果
列表里嵌套列表
service2 = [['http',80],['ssh',22],['ftp',21]]
#1.索引
print(service2[1][1])
print(service2[-1][1])
#2.切片
print(service2[:][1])
print(service2[:-1][0])
print(service2[::-1][0])
print(service2[0][:-1])
结果
练习
name = ['fentiao','fendai','fensi','apple']
print('I have %s,%s,%s and %s.'%(name[0],name[1],name[2],name[3])) ##方法1
print('I have ' + (',').join(name[:-1]) + ' and ' + name[-1]+'.') ##方法2
结果
列表的增加,删除,修改,查看
列表的增加
用+[’’]的方式
append(‘元素’) 追加一个元素
extend([‘元素1’,'元素2 ']) 追加多个元素
insert(索引值,‘元素’)
service = ['http','ssh','ftp']
#1.
print(service + ['firewalld'])
#2.append:追加一个元素到列表中
service.append('firewalld')
print(service)
#3.extend:拉伸 追加多个元素到列表中
service.extend(['mysql','firewalld'])
print(service)
#4.insert:在指定索引位置插入元素
service.insert(1,'samba')
print(service)
结果
列表元素的删除
pop() 弹出最后一个元素
pop(1) 弹出索引值为1的元素
remove(‘元素’) 移除元素
clear() 清空列表里所有元素
del(python关键字) 从内存中删除列表
pop弹出
In [12]: service = ['http','ssh','ftp']
In [13]: service.pop()
Out[13]: 'ftp'
In [14]: service
Out[14]: ['http', 'ssh']
In [15]: service.pop()
Out[15]: 'ssh'
In [16]: service
Out[16]: ['http']
In [17]: service.pop()
Out[17]: 'http'
In [18]: service
Out[18]: []
remove 删除
#remove:删除指定元素
service = ['http', 'ssh', 'ftp']
a = service.remove('ssh')
print(service)
print(a)
结果
del 在内存中删除
service = ['http','ftp','ssh']
print(service)
del service
print(service)
结果
clear
service = ['http', 'ssh', 'ftp']
service.clear() #清空列表里面的所有元素
print(service)
列表的修改
(1)通过索引,重新赋值
service = ['http','ssh','ftp']
service[0] = 'mysql'
print(service)
结果
(2)通过切片
service = ['http','ssh','ftp']
print(service[:2])
service[:2] = ['samba','ldap']
print(service)
结果
列表的查看
(1)查看出现的次数
service = ['ftp','http','ssh','ftp']
print(service.count('ftp'))
结果
(2)查看指定元素的索引值(可以指定索引范围查看)
service = ['ftp','http','ssh','ftp']
print(service.index('ssh'))
print(service.index('ftp',0,3))列表的查看
结果
列表中的排序
ASCII顺序查看
service = ['ftp','http','ssh','ftp']
#排序查看 按照ASCII顺序
service.sort()
print(service)
结果
逆序排序
service = ['ftp','http','ssh','ftp']
service.sort(reverse=True)
print(service)
结果
打乱列表顺序
import random
li = list(range(10))
print(li)
#将原有的列表顺序打乱
random.shuffle(li)
print(li)
结果
练习
系统里面有多个用户,用户的信息目前保存在列表里面
users = [‘root’,‘westos’]
passwd = [‘123’,‘456’]
2.用户登陆(判断用户登陆是否成功
1).判断用户是否存在
2).如果存在
1).判断用户密码是否正确
如果正确,登陆成功,推出循环
如果密码不正确,重新登陆,总共有三次机会登陆
3).如果用户不存在
重新登陆,总共有三次机会
代码
user = ['root','westos']
password = ['123','456']
trycount = 0
while trycount < 3:
inuser = input('Username:')
inpass = input('Password:')
if inuser in user:
index = user.index(inuser)
if inpass == password[index]:
print('Login Success!')
break
else:
print(' Password error!')
trycount += 1
else:
print('%s is not exist!'%inuser)
trycount += 1
else:
print('no more chance!')
结果
- 后台管理员只有一个用户: admin, 密码: admin
- 当管理员登陆成功后, 可以管理前台会员信息.
- 会员信息管理包含:
添加会员信息
删除会员信息
查看会员信息
退出
代码
print('管理员登录'.center(50,'*'))
inuser = input('UserName:')
inpasswd = input('Password:')
#所有会员用户名
users = ['root','westos']
#所有会员密码
passwds = ['123','456']
if inuser == 'admin' and inpasswd == 'admin':
print('管理员登录成功!')
print('会员管理'.center(50,'*'))
while True:
print("""
操作目录
1. 添加会员信息
2. 删除会员信息
3. 查看会员信息
4. 退出
""")
choice = input('请选择你的操作:')
if choice == '1':
print('添加会员信息'.center(50,'*'))
AddUser = input('添加会员名:')
if AddUser in users:
print('用户%s已经存在' %(AddUser))
else:
AddPasswd = input('密码:')
users.append(AddUser)
passwds.append(AddPasswd)
print('添加用户%s成功!' %AddUser)
elif choice == '2':
print('删除会员信息'.center(50,'*'))
DelUser = input('删除会员名:')
DelIndex = users.index(DelUser)
users.remove(DelUser)
passwds.pop(DelIndex)
print('删除会员%s成功!' %DelUser)
elif choice == '3':
print('查看会员信息'.center(50,'*'))
print('\t用户名\t密码')
UserCount = len(users)
for i in range(UserCount):
print('\t%s\t%s' %(users[i],passwds[i]))
elif choice == '4':
exit()
else:
print('请输入正确的选择')
else:
print('管理员登录失败!')
测试
用列表实现栈的工作原理
栈的工作原理:
入栈
出栈
查看栈顶元素
栈的长度
栈是否为空
代码
stack = []
info = """
栈操作
1.入栈
2.出栈
3.栈顶元素
4.栈的长度
5.栈是否为空
q.退出
"""
while True:
print(info)
choice = input('请输入选择:')
if choice == '1':
item = input('入栈元素:')
stack.append(item)
print('元素%s入栈成功' %item)
elif choice == '2':
#先判断栈是否为空
if not stack:
print('栈为空,不能出栈')
else:
item = stack.pop()
print('%s元素出栈成功' %item)
elif choice == '3':
if len(stack) == 0:
print('栈为空')
else:
print('栈顶元素为%s' %(stack[-1]))
elif choice == '4':
print('栈的长度为%s' %(len(stack)))
elif choice == '5':
if len(stack) == 0:
print('栈为空')
else:
print('栈不为空')
elif choice == 'q':
print('退出')
break
else:
print('请输入正确的选择')
测试
元组 tuple
元组为阉割版的列表,元组本身为不可变数据类型,无增删改查功能。但元组内可以存储任意数据类型。
元组的表示: 小括号 ‘( )‘
元组的创建
t = (1,2.3,True,'star')
print(t)
print(type(t))
```javascript
#元组里面包含可变数据类型,可以间接修改元组的内容
t1 = ([1,2,3],4)
t1[0].append(4)
print(t1)
#元组如果只有一个元素的时候,后面一定要加逗号,否则数据类型不确定
t2 = ('hello')
t3 = (1,)
print(type(t2))
print(type(t3))
结果
元组的特性(索引,切片,重复,连接,成员操作符,迭代)
索引 切片
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
print(allowUsers[0])
print(allowUsers[-1])
print(allowUsers[1:])
print(allowUsers[2:])
print(allowUsers[:-1])
print(allowUsers[::-1])
结果
重复
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
print(allowUsers * 3)
结果
连接
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
print(allowUsers + ('linux','python'))
结果
成员操作符
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
print('westos' in allowUsers)
print('westos' not in allowUsers)
结果
for循环(迭代)
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
for user in allowUsers:
print(user)
for index,user in enumerate(allowUsers):
print('第%d个白名单用户: %s' %(index+1,user))
结果
zip:两个元组的元素之间一一对应
allowUsers = ('root','westos','redhat')
allowPasswd = ('123','456','789')
for user,passwd in zip(allowUsers,allowPasswd):
print(user,':',passwd)
结果
元组中常用的内置方法
(1)索引
(2)出现的次数
t = (1,2.3,True,'westos','westos')
print(t.count('westos')) ##出现次数
print(t.index(2.3)) ##索引
结果
元组的应用场景
变量交换数值
a = 1
b = 2
b,a = a,b
#1.先把(a,b)封装成一个元组(1,2)
#2.b,a=a,b ---> b,a=(1,2)
#b = (1,2)[0] a = (1,2)[1]
print(a)
print(b)
结果
打印变量的值
name = 'westos'
age = 11
t = (name,age)
print('name:%s , age:%d' %(name,age))
print('name:%s , age:%d' %t)
结果
元组的赋值
#有多少个元素,就用多少个变量接收
t = ('westos',11,100)
name,age,score = t
print(name,age,score)
元组排序
#类型转换为列表用.sort()排序
score = (100,89,45,78,65)
scoreLi = list(score) ##转换为列表的输出为:[100, 89, 45, 78, 65]
scoreLi.sort() ##排序后:[45, 65, 78, 89, 100]
print(scoreLi)
结果
去掉一个最大数,去掉一个最小数,求平均成绩
score = (100,89,45,78,65)
scores = sorted(score) ##scores = [45, 65, 78, 89, 100]
minscore,*middlescore,maxscore = scores ##用排序后的
print(minscore)
print(middlescore)
print(maxscore)
print('最终成绩为: %.2f' %(sum(middlescore) / len(middlescore)))
结果
集合
集合的定义
集合是无序的数据类型,使用’{}‘可以定义集合。
特点:集合中的元素不可重复,故常被用到去重。
s = {1,2,3,1,2,3,4,5}
print(s)
print(type(s))
s1 = {1} ##只有一个元素也不用加逗号
print(s1)
print(type(s1))
结果
如何定义一个空集合
定义方式:s3 = set([])
s3 = set([])
print(s3)
print(type(s3))
结果
集合的应用——>(去重)
li = [1,2,3,1,2,3]
print(list(set(li))) ##先转换成集合,则自动去重,然后再转回列表形式
结果:
[1, 2, 3]
集合的特性
成员操作符
s = {1,2,3}
print(1 in s)
结果
for循环
s = {1,2,3}
for i in s:
print(i,end='|')
for i,v in enumerate(s):
print('index: %s,value: %s' %(i,v))
结果
集合的常用方法(删除与增加,并集,交集,差集,对等差分,超集)
集合:无序的数据类型
添加顺序和在集合中存储的顺序是不一定相同的
增加和删除
s = {6,7,8,9}
#增加一个元素
s.add(1)
print(s)
#增加多个元素
s.update({5,3,2})
print(s)
#删除
s.pop()
print(s)
#删除指定元素
s.remove(5)
print(s)
结果
并集,交集,差集,对等差分
s1 = {1,2,3}
s2 = {2,3,4}
#并集
print('并集:',s1.union(s2))
print('并集:',s1|s2)
#交集
print('交集:',s1.intersection(s2))
print('交集:',s1&s2)
#差集
print('差集:',s1.difference(s2)) #s1-(s1&s2)
print('差集:',s2.difference(s1)) #s2-(s1&s2)
#对等差分:并集-交集
print('对等差分:',s2.symmetric_difference(s1))
print('对等差分:',s1^s2)
结果
超集
s4 = {1,2,3}
#s3是否为s4的超集
#超集:如果s3中的每一个元素都在集合s4中,且s4中可能包含s3中没有的元素,
#那么s4就是s3的一个超集
print(s3.issuperset(s4))
print(s4.issuperset(s3))
#s3是否为s4的子集
print(s3.issubset(s4))
#两个集和是不是 不相交
print(s3.isdisjoint(s4))
结果
字典
字典是一个无序的数据集合,通常使用print输出字典的顺序和定义的顺序是不一样的。
字典就是键值对。中间以冒号隔开,除了结尾的键值对,其余键值对后加逗号。
一个key值可以对应多个value值,且value值类型不限
字典的创建与定义
users = ['user1','user2']
passwd = ['123','456']
print(zip(users,passwd))
print(list(zip(users,passwd)))
print(dict(zip(users,passwd)))
s = {}
print(type(s))
结果
s = {
'linux':[100,99,88],
'westos':[190,564,645]
}
print(s)
print(type(s))
结果
工厂函数
d = dict()
print(d)
print(type(d))
{}
<class 'dict'>
d1 = dict(a=1,b=2)
print(d1)
print(type(d1))
{'a': 1, 'b': 2}
<class 'dict'>
字典的嵌套
students = {
'03113009':{
'name':'tom',
'age':18,
'score':80
},
'03113010':{
'name': 'laoli',
'age': 19,
'score':30
}
}
print(students['03113010']['name'])
所有的key和value值是一样的情况(使用.fromkey)
print({}.fromkeys({'1','2'},'03113009'))
结果:
{'2': '03113009', '1': '03113009'}
字典的特性
不支持索引、切片;并且字典的重复、连接是无意义的(因为key是唯一的)
成员操作符
判断的是某个值是否为字典的key
d = {
'1':'a',
'2':'b'
}
print('1' in d)
print('1' not in d)
结果
for循环
默认遍历字典的key值
d = {
'1':'a',
'2':'b'
}
for key in d:
print(key)
结果
遍历字典
d = {
'1':'a',
'2':'b'
}
第一种:
for key in d:
print(key,d[key])
第二种:
for key,value in d.items():
print(key,value)
结果
字典的增加,删除,查看
字典的增加
增加一个元素
如果key值存在,则更新对应的value值
如果key值不存在,则添加对应的key-value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
service['mysql'] = 3306
print(service)
service['http'] = 443
print(service)
结果
添加多个key-value值
如果key值存在,则更新对应的value值
如果key值不存在,则添加对应的key-value值
service_backup = {
'https':443,
'tomcat':8080,
'http':8080
}
service.update(service_backup)
print(service)
service.update(flask=9000,http=8000)
print(service)
结果
结果:
{'http': 8080, 'ftp': 21, 'ssh': 22, 'mysql': 3306, 'https': 443, 'tomcat': 8080}
{'http': 8000, 'ftp': 21, 'ssh': 22, 'mysql': 3306, 'https': 443, 'tomcat': 8080, 'flask': 9000}
setdefault添加key值
如果key值存在,不做修改
如果key值不存在,则添加对应的key-value
service.setdefault('http',9090)
print(service)
service.setdefault('oracle',44575)
print(service)
结果
字典的删除
del
service = {
'http':80,
'ftp':21,
'ssh':22
}
del service['http']
print(service)
结果
pop:删除指定key的key-value
如果key存在,删除,并且返回删除key对应的value
如果key不存在,报错
service = {
'http':80,
'ftp':21,
'ssh':22
}
item = service.pop('http')
print(item)
print(service)
结果
popitem:删除最后一个key-value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
item = service.popitem()
print('删除的key-value对是:',item)
print(service)
结果
clear:清空字典内容
service.clear()
print(service)
结果:
{}
字典的查看
查看字典的key值
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.keys())
结果
查看字典的value值
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.values())
结果
查看key的value值
key不存在,报错
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service['https']) ##会报错
遍历
service = {
'http':80,
'ftp':21,
'ssh':22
}
for k,v in service.items():
print(k,'--->',v)
结果
get方法获取指定key对应的value值
如果key值存在,返回对应的value值
如果key值不存在,默认返回None,如果需要指定返回值,传值即可
service = {
'http':80,
'ftp':21,
'ssh':22
}
print(service.get('https',443))
print(service.get('https'))
service = {
'http':80,
'ftp':21,
'ssh':22
}
第一种写法:
print(service.get('https','ket not exist'))
另一种写法:
print(service['http'])
if 'https' in service:
print(service['https'])
else:
print('key not exist')
结果