>>> alist = [10, 8, 20]
>>> alist[0] = 100
>>> alist
[100, 8, 20]
>>> alist[1:3]
[8, 20]
>>> alist[1:3] = [1, 2, 3, 4, 6]
>>> alist
[100, 1, 2, 3, 4, 6]
>>> alist = [1, 2, 3, 4, 5, 6]
>>> alist.append(1000) # 追加
>>> alist
[1, 2, 3, 4, 5, 6, 1000]
>>> alist.extend((1,2)) # 把序列对象中的每项作为元素进行添加
>>> alist
[1, 2, 3, 4, 5, 6, 1000, 1, 2]
>>> alist.append((3,4)) # 把元组追加到列表末尾
>>> alist
[1, 2, 3, 4, 5, 6, 1000, 1, 2, (3, 4)]
>>> alist.remove((3,4)) # 删除列表中的某一项
>>> alist
[1, 2, 3, 4, 5, 6, 1000, 1, 2]
>>> alist.reverse() # 翻转列表
>>> alist
[2, 1, 1000, 6, 5, 4, 3, 2, 1]
>>> alist.insert(1,1111) # 在下标为1的地方插入数据1111
>>> alist
[2, 1111, 1, 1000, 6, 5, 4, 3, 2, 1]
>>> alist.sort() # 升序排列
>>> alist
[1, 1, 2, 2, 3, 4, 5, 6, 1000, 1111]
>>> alist.sort(reverse=True) # 降序排列
>>> alist
[1111, 1000, 6, 5, 4, 3, 2, 2, 1, 1]
>>> alist.count(1) # 统计列表中数据1出现的次数
2
>>> alist.pop() # 默认将最后一个数据弹出
1
>>> alist
[1111, 1000, 6, 5, 4, 3, 2, 2, 1]
>>> alist.pop(0) # 将下标为0的数据弹出
1111
>>> alist
[1000, 6, 5, 4, 3, 2, 2, 1]
>>> alist.index(2) # 取出第一个数据2的下标
5
>>> blist = alist.copy() # 将alist的值拷贝出来,赋值给blist
>>> blist
[1000, 6, 5, 4, 3, 2, 2, 1]
>>> blist.clear() # 清空blist
>>> blist
[]
>>> alist
[1000, 6, 5, 4, 3, 2, 2, 1]
>>> atu = (10, 20, 30)
>>> atu
(10, 20, 30)
>>> atu.
atu.count( atu.index(
>>> atu.count(100) # 统计数据100在元组中出现的次数
0
>>> atu.index(20) # 查看数据20在元组中的下标
1
如果一个元组中只有一个元素,那么创建该元组的时候,需要肩上一个逗号
>>> a = (10)
>>> type(a)
<class 'int'>
>>> a = (10,)
>>> type(a)
<class 'tuple'>
>>> len(a)
1
用列表构建栈结构
思路:
1.考虑程序的运行方式
2.分析程序有哪些功能,将这些功能编写成函数
3.编写主程序代码,按相关的规则调用函数
# 定义全局变量
stack = []
def push_it(): # 实现压栈功能
data = input('数据:')
if data:
stack.append(data)
else:
print('数据不能为空!')
def out_it(): # 实现出栈功能
print(stack.pop())
def view_it(): # 实现查询功能
print(stack)
def show_menu(): # 交互界面显示功能
choose = {'0': push_it,'1': out_it,'2': view_it}
while True:
choice = input('''(0) 压栈
(1) 出栈
(2) 查询
(3) 退出
请输入选择(0/1/2/3):''')
if choice not in ['0', '1', '2', '3']:
print('无效选项!!!')
continue
if choice == '3':
print('退出成功~')
break
choose[choice]()
if __name__ == '__main__': # 主程序
show_menu()
>>> adict = dict(['ab', ('name', 'bob'), ['age', 20]])
>>> adict
{'a': 'b', 'name': 'bob', 'age': 20}
# 创建具有相同值的字典
>>> bdict = {}.fromkeys(adict,7)
>>> bdict
{'a': 7, 'name': 7, 'age': 7}
# 访问字典
>>> for i in adict:
... print(i,adict[i])
a b
name bob
age 20
>>> '%(name)s is %(age)s old' % adict
'bob is 20 old'
# 赋值时,若key在字典中,则更新key对应的值,若不在,则在字典中新增键值对
>>> adict['age'] = 25
>>> adict['email'] = '[email protected]'
>>> 'bob' in adict # 'bob'不是字典的key值
False
>>> 'name' in adict
True
>>> adict
{'a': 'b', 'name': 'bob', 'age': 25, 'email': '[email protected]'}
>>> len(adict)
4
# 字典最常用的方法
>>> adict.get('name')
'bob'
>>> adict['lisis'] # 对应的key值在字典中不存在,报错
Traceback (most recent call last):
File "" , line 1, in <module>
KeyError: 'lisis'
>>> adict.get('lisis')
>>> print(adict.get('lisis')) # 报错则返回值为None
None
>>> print(adict.get('lisis', 'not found'))
not found
# 去除所有的key值
>>> list(adict.keys())
['a', 'name', 'age', 'email']
# 取出所有value值
>>> adict.values()
dict_values(['b', 'bob', 25, '[email protected]'])
>>> list(adict.values())
['b', 'bob', 25, '[email protected]']
# 取出所有的键值对
>>> list(adict.items())
[('a', 'b'), ('name', 'bob'), ('age', 25), ('email', '[email protected]')]
# 根据key弹出字典的一项
>>> adict.pop('a')
'b'
# 批量向字典加入数据
>>> adict.update({'qwe': '123456','qq': '123'})
模拟用户登陆信息系统
import getpass
userdb = {}
def add_user(): # 用户注册
uname = input('name:').strip()
if uname in userdb:
print('用户名已存在')
else:
upass = input('密码:').strip()
userdb[uname] = upass
print('注册成功!!')
return
def into_user(): # 用户登录
uname = input('name:')
upass = getpass.getpass('密码:') 登录时,密码不显示输入
if userdb.get(uname) == upass:
print('登录成功!!')
else:
print('用户名或密码错误,请重试')
return
def show_menu(): # 显示界面
choose = {'0': into_user, '1': add_user}
while True:
choice = input('''0 登录
1 注册
2 退出
请选择(0/1/2):''')
if choice not in ['0', '1', '2']:
print('无效输入,请重新输入!')
continue
if choice == '2':
print('退出成功~~~')
break
choose[choice]()
if __name__ == '__main__':
show_menu()
>>> s1 = set('asd')
>>> s2 = set('zxc')
>>> s3 = set(['qqq', 'www', 'eee'])
>>> s1
{'a', 's', 'd'}
>>> s2
{'c', 'z', 'x'}
>>> s3
{'eee', 'www', 'qqq'}
>>> set('qqwwee')
{'w', 'q', 'e'}
# 成员判断
>>> 'qwe' in s3
False
>>> 'qqq' in s3
True
# 交集,两个集合中都包含的元素
>>> s1
{'z', 's', 'w', 'q', 'e', 'x', 'd', 'a'}
>>> s2
{'c', 'z', 'x'}
>>> s1 & s2
{'z', 'x'}
# 并集,两个集合中全部元素
>>> s1 | s2
{'z', 's', 'w', 'q', 'e', 'x', 'd', 'c', 'a'}
# 差补,s1中有 s2中没有
>>> s1 - s2
{'s', 'w', 'q', 'e', 'd', 'a'}
# 创建空集合
>>> s3 = set('')
>>> s3
set()
>>> type(s3)
<class 'set'>
# 添加元素
>>> s3.add(10)
>>> s3
{10}
>>> s3.add([20,30]) # 错误,因为列表是可变的,但集合的元素要求是不可变
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: unhashable type: 'list'
>>> s3
{10}
>>> s3.update([20,30]) # 将列表的元素添加到集合中
>>> s3
{10, 20, 30}
# 删除元素
>>> s3.remove(30)
>>> s3
{10, 20}
# s3是s4的子集吗
>>> s3.issubset(s4)
True
# s4是s3的超集吗
>>> s4.issuperset(s3)
True
# s1 & s2
>>> s1.intersection(s2)
{'z', 'x'}
# s1 | s2
>>> s1.union(s2)
{'z', 's', 'w', 'q', 'e', 'x', 'd', 'c', 'a'}
# s1 - s2
>>> s1.difference(s2)
{'s', 'w', 'q', 'e', 'd', 'a'}
>>> from random import randint
>>> nums = [randint(1,20) for i in range(20)]
>>> nums
[12, 14, 10, 10, 4, 11, 8, 7, 9, 3, 10, 20, 14, 15, 20, 16, 8, 12, 7, 11]
>>> nums = set(randint(1,20) for i in range(20))
>>> nums
{2, 3, 4, 5, 6, 7, 8, 12, 13, 15, 16, 18, 20}
>>> nums = list(set(randint(1,20) for i in range(20)))
>>> nums
[2, 3, 6, 7, 8, 9, 10, 11, 12, 15, 16, 17, 18]
比较两个文件,取出是第2个文件有而第1个文件没有的行
(Pytest) [student@room9pc01 day05]$ cp /etc/passwd /tmp/mima1
(Pytest) [student@room9pc01 day05]$ cp /etc/passwd /tmp/mima2
# 修改文件,是文件产生不同于mima1的行
(Pytest) [student@room9pc01 day05]$ vim /tmp/mima2
>>> with open('/tmp/mima1','r') as f1:
... s1 = set(f1)
...
>>> with open('/tmp/mima2', 'r') as f2:
... s2 = set(f2)
...
>>> s1 - s2
set()
>>> s2 -s1
{'asdjiuadjokgpso\n', 'asdahdua\n'}
>>> with open('/tmp/mima3','w') as f3:
... f3.writelines(s2 - s1)