py基础-列表、元组、字典以及集合

Python基础篇 仅你 共享
上次编辑时间: 7月 27, 2020


image.png

列表,元组,字典,集合
列表:
属于容器,可变,序列
创建以及访问列表:

>>> import random
#创建具有5个随机数字的列表
>>> alist = [random.randint(1,100) for i in range(5)]
>>> alist
[10, 15, 40, 5, 50]
#赋值
>>> alist[-1] = 21
>>> alist
[10, 15, 40, 5, 21]
>>> alist[1:3] = [1,3,5,7,9]
>>> alist
[10, 1, 3, 5, 7, 9, 5, 21]
#追加
>>> alist.append(5)
>>> alist
[10, 1, 3, 5, 7, 9, 5, 21, 5]
>>> alist.insert(0,5)
>>> alist
[5, 10, 1, 3, 5, 7, 9, 5, 21, 5]
>>> alist.count(5) #统计5出现的次数
4
>>> alist.index(5) ---返回第一个5的下标
0
>>> alist.append([1,2])
>>> alist
[5, 10, 1, 3, 5, 7, 9, 5, 21, 5, [1, 2]]
>>> alist.extend([1,2])
>>> alist
[5, 10, 1, 3, 5, 7, 9, 5, 21, 5, [1, 2], 1, 2]
#默认从末尾开始弹出
>>> alist.pop()
2
>>> alist
[5, 10, 1, 3, 5, 7, 9, 5, 21, 5, [1, 2], 1]
>>> alist.pop(-2)#弹出下标为-2 的值
>>> alist.pop(5)#弹出下标为5的值
7
>>> alist
[5, 10, 1, 3, 5, 9, 5, 21, 5, 1]
>>> alist.insert(3,86)
>>> alist
[5, 10, 1, 86, 3, 5, 9, 5, 21, 5, 1]
>>> alist.remove(86)
>>> alist
[5, 10, 1, 3, 5, 9, 5, 21, 5, 1]
>>> alist.remove(5) #删除数字5,从左向右开始删除
>>> a = alist.pop() #将pop的返回值赋值给a
>>> a
1
>>> b = alist.remove(5) # remove没有返回值,默认返回None
>>> b
>>> alist
[10, 1, 3, 9, 5, 21, 5]
>>> alist.reverse()
>>> alist
[5, 21, 5, 9, 3, 1, 10]
>>> alist.sort() #默认升序
>>> alist
[1, 3, 5, 5, 9, 10, 21]
>>> alist
[1, 3, 5, 5, 9, 10, 21]
>>> alist.sort(reverse=True) #降序
>>> alist
[21, 10, 9, 5, 5, 3, 1]
>>> blist = alist.copy() #将alist的值赋值给blist, 但是采用不同内存空间
>>> alist
[21, 10, 9, 5, 5, 3, 1]
>>> blist
[21, 10, 9, 5, 5, 3, 1]
>>> blist.clear() #清空列表
>>> blist
[]
>>> alist
[21, 10, 9, 5, 5, 3, 1]
元组:
属于容器,不可变,序列
创建元组:
>>> 'hello'.count('l')
2
>>> 'hello'.index('l')
2
>>> atuple = (12, 20, 16, 25,22)
>>> atuple.count(12)
1
>>> atuple.index(12)
0#单元组
>>> a = ('hello')
>>> type(a)

>>> a
'hello'
>>> b = ('hello',) #加逗号为了将其变成元组
>>> type(b)

>>> b
('hello',)
>>> len(b)
1

列表练习:

1.程序的运行方式
1. 程序的运行方式
```shell
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): abc
无效的输入,请重试。
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 2
[]
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 0
数据:
输入为空
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 0
数据: hello
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 0
数据: world
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 2
['hello', 'world']
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 1
从栈中弹出了: world
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 1
从栈中弹出了: hello
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 1
空栈
(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请选择(0/1/2/3): 3
Bye-bye
  1. 框架
def push_it():
def pop_it():
def view_it():
def show_menu():
if __name__ == '__main__':
 show_menu()

3. 完成每个函数
2.程序代码
    cmds = {'0':push_it,'1':pop_it,'2':view_it}  #这才是调用函数
    menu = """(0)压栈:
(1)出栈:
(2)查询:
(3)退出:
请选择(0/1/2/3):"""
    while 1:
        choice = input(menu).strip()#去除两端空白
        if choice not in ['0','1','2','3']:
            print('\033[031;1m无效的输入,请重试: \033[0m')
            continue
        if choice == '3':
            print('bye-bye')
            break
        cmds[choice]()
stack = []
def push_it():
 data = input('数据: ').strip()
 if data : #非空字符串为真
 stack.append(data)
 else:
 print('\033[31;1m输入为空\033[0m')
def pop_it():
 if stack : #列表非空为真
 print('从栈中弹出了: \033[34;1m%s\033[0m' % stack.pop())
 else:
 print('\033[31;1m空栈\033[0m')
def view_it():
 print('\033[31;1m%s\033[0m' % stack)
def show_menu():
# try:
 menu = """(0)压栈:
(1)出栈:
(2)查询:
(3)退出:
请选择(0/1/2/3):"""
 while 1:
 choice = input(menu).strip()#去除两端空白
 if choice not in ['0','1','2','3']:
 print('无效的输入,请重试: ')
 continue
 if choice == '0':
 push_it()
 elif choice == '1':
 pop_it()
 elif choice == '2':
 view_it()
 else:
 break
 print('bye-bye')
 # except:
 # print('请按照菜单输入相应数字')
if __name__ == '__main__':
 show_menu()
stack = []
stack = []
def push_it():
 data = input('数据: ').strip()
 if data : #非空字符串为真
 stack.append(data)
 else:
 print('\033[31;1m输入为空\033[0m')
def pop_it():
 if stack : #列表非空为真
 print('从栈中弹出了: \033[34;1m%s\033[0m' % stack.pop())
 else:
 print('\033[31;1m空栈\033[0m')
def view_it():
 print('\033[31;1m%s\033[0m' % stack)
def show_menu():
# try:
 #cmds = {'0':push_it(),'1':pop_it(),'2':view_it()} ----把函数的值(返回值None)放到字典里
 cmds = {'0':push_it,'1':pop_it,'2':view_it} #这才是调用函数
 menu = """(0)压栈:
(1)出栈:
(2)查询:
(3)退出:
请选择(0/1/2/3):"""
 while 1:
 choice = input(menu).strip()#去除两端空白
 if choice not in ['0','1','2','3']:
 print('\033[031;1m无效的输入,请重试: \033[0m')
 continue
 if choice == '3':
 print('bye-bye')
 break
 cmds[choice]()
 # except:
 # print('请按照菜单输入相应数字')
if __name__ == '__main__':
 show_menu()

字典:
属于容器,可变,映射类型
字典的键不能重复
字典的key只能是不可变的 ---数字,字符,元组
创建字典:

>>> dict(['ab','cd','ef'])
{'a': 'b', 'c': 'd', 'e': 'f'}
>>> dict([('name','tom'),('age',20)])
{'name': 'tom', 'age': 20}
>>> dict([['name','tom'],['age',20]])
{'name': 'tom', 'age': 20}
>>> dict(['ab' ,['name','tom'],('age',20)])
{'a': 'b', 'name': 'tom', 'age': 20}
>>> {}.fromkeys(('tom','jerry','bob','alice'),7)
{'tom': 7, 'jerry': 7, 'bob': 7, 'alice': 7}
>>> adict = dict(['ab', ['name', 'tom'], ('age', 20)]) ---
>>> adict
{'a': 'b', 'name': 'tom', 'age': 20}
>>> 'tom' in adict
False
>>> 'name' in adict
True
>>> for key in adict:
... print(key, adict[key])
...
a b
name tom
age 20
>>> '%s is %s years old' % (adict['name'],adict['age'])
'tom is 20 years old'
>>> '%(name)s is %(age)s years old' % adict
'tom is 20 years old'
>>> adict['age'] = 22 #键存在,则更新值
>>> adict
{'a': 'b', 'name': 'tom', 'age': 22}
>>> adict['email'] = '[email protected]' #键不存在,则创建添加
>>> adict
{'a': 'b', 'name': 'tom', 'age': 22, 'email': '[email protected]'}
>>> del adict['a'] #删除字典中的键
>>> adict
{'name': 'tom', 'age': 22, 'email': '[email protected]'}

元组可以作为key,列表不行,因为列表可变

>>> {(10,15):'tom'}
{(10, 15): 'tom'}

通过key获取值------用得最广泛最重要的

>>> adict.get('name')
'tom'
>>> adict.get('names', 'not found')#key不存在返回后者
'not found'
>>> adict.keys()
dict_keys(['name', 'age', 'email'])
>>> adict.values()
dict_values(['tom', 22, '[email protected]'])
>>> adict.items()
dict_items([('name', 'tom'), ('age', 22), ('email', '[email protected]')])
>>> adict.pop('name') #弹出字典key
'tom'
>>> adict.update({'age':23})
>>> adict
{'age': 23, 'email': '[email protected]', 'name': 'tom'}

模拟用户登录信息系统:

import getpass
userdb = {}
def register():
 username = input('用户名: ').strip()
 if not username:
 print('用户名不能为空')
 elif username in userdb:
 print('用户已存在')
 else:
 password = input('密码: ')
 userdb[username] =password
def login():
 username = input('用户名: ').strip()
 password = getpass.getpass('密码: ')
 #if (username in userdb) and (userdb[username] == password):
 if userdb.get(username) == password:
 print('登录成功')
 else:
 print('登录失败')
def show_menu():
 cmds = {'0':register, '1':login}
 menu = """(0) 注册
(1) 登录
(2) 退出
请选择(0/1/2): """
 while 1:
 choice = input(menu).strip()
 if choice not in ['0','1','2']:
 print('请输入提示信息,谢谢')
 continue
 if choice == '2' :
 print('bye-bye')
 break
 cmds[choice]()
if __name__ == '__main__':
 show_menu()

集合:
不同元素组成
元素不能重复
元素必须是不可变对象
元素没有顺序
集合就像是一个无值的字典
分类:可变集合set,不可变集合frozenset

创建集合

>>> aset = set('abcd')
>>> aset
{'d', 'c', 'a', 'b'}
>>> set(['tom','jerry','bob'])
{'tom', 'bob', 'jerry'}
>>> bset = set('bcd')
>>> bset
{'d', 'c', 'b'}
>>> 'a' in bset
False
>>> len(aset)
4
>>> for ch in aset:
... print(ch)
...
dcab
>>> aset & bset #交集
{'d' ' ' 'b'}
添加标签
{'d', 'c', 'b'}
>>> aset | bset #并集
{'c', 'a', 'd', 'b'}
>>> aset - bset #差补,aset有,bset中没有的
{'a'}
>>> cset = set('abc')
>>> cset.add('hello') ---添加
>>> cset
{'c', 'a', 'hello', 'b'}
>>> cset.update('hello')---相当于列表extend添加
>>> cset
{'c', 'a', 'e', 'hello', 'h', 'l', 'b', 'o'}
>>> cset.update(['nimade','chishi'])
>>> cset
{'x', 'c', 'a', 'hello', 'h', 'l', 'b', 'o', 'nimade', 'chishi', 'i'}
>>> cset.remove('e')
>>> cset
{'c', 'a', 'hello', 'h', 'l', 'b', 'o'}
>>> cset
{'c', 'a', 'e', 'b', 'd'}
>>> dset
{'d', 'c', 'b'}
>>> cset.issuperset(dset)---c是d的超集(包含)
True
>>> dset.issubset(cset) ----d是c的子集
True

去重:(两个文件之间的差异,例如访问url,每天的访问页面有哪些)

##去重##
# [root@room9pc01 local.d]# cp /etc/passwd /tmp/mima1
# [root@room9pc01 local.d]# cp /etc/passwd /tmp/mima2
# [root@room9pc01 local.d]# vim /tmp/mima2
# >>> with open('/tmp/mima1') as f1:
# ... aset = set(f1)
# >>> with open('/tmp/mima2') as f2:
# ... bset = set(f2)
# >>> bset - aset
# >>> with open('/tmp/result.txt' , 'w' ) as f3:
# ... f3.writelines(bset - aset)

你可能感兴趣的:(py基础-列表、元组、字典以及集合)