• 【python零基础入门学习】python基础篇(基础结束篇)之数据结构类型-列表,元组,字典,集合(五)


      本站以分享各种运维经验和运维所需要的技能为主

    《python零基础入门》:python零基础入门学习

    《python运维脚本》: python运维脚本实践

    shell》:shell学习

    《terraform》持续更新中:terraform_Aws学习零基础入门到最佳实战

    《k8》暂未更新

    docker学习》暂未更新

    《ceph学习》ceph日常问题解决分享

    《日志收集》ELK+各种中间件

    《运维日常》运维日常

     

    列表:

    • 属于容器,可变,序列

    创建以及访问列表:

    1. >>> import random
    2. #创建具有5个随机数字的列表
    3. >>> alist = [random.randint(1,100) for i in range(5)]
    4. >>> alist
    5. [10, 15, 40, 5, 50]
    6. #赋值
    7. >>> alist[-1] = 21
    8. >>> alist
    9. [10, 15, 40, 5, 21]
    10. >>> alist[1:3] = [1,3,5,7,9]
    11. >>> alist
    12. [10, 1, 3, 5, 7, 9, 5, 21]
    13. #追加
    14. >>> alist.append(5)
    15. >>> alist
    16. [10, 1, 3, 5, 7, 9, 5, 21, 5]
    17. >>> alist.insert(0,5)
    18. >>> alist
    19. [5, 10, 1, 3, 5, 7, 9, 5, 21, 5]
    20. >>> alist.count(5) #统计5出现的次数
    21. 4
    22. >>> alist.index(5)  ---返回第一个5的下标
    23. 0
    24. >>> alist.append([1,2])
    25. >>> alist
    26. [5, 10, 1, 3, 5, 7, 9, 5, 21, 5, [1, 2]]
    27. >>> alist.extend([1,2])
    28. >>> alist
    29. [5, 10, 1, 3, 5, 7, 9, 5, 21, 5, [1, 2], 1, 2]
    30. #默认从末尾开始弹出
    31. >>> alist.pop()
    32. 2
    33. >>> alist
    34. [5, 10, 1, 3, 5, 7, 9, 5, 21, 5, [1, 2], 1]
    35. >>> alist.pop(-2)#弹出下标为-2 的值
    36. >>> alist.pop(5)#弹出下标为5的值
    37. 7
    38. >>> alist
    39. [5, 10, 1, 3, 5, 9, 5, 21, 5, 1]
    40. >>> alist.insert(3,86)
    41. >>> alist
    42. [5, 10, 1, 86, 3, 5, 9, 5, 21, 5, 1]
    43. >>> alist.remove(86)
    44. >>> alist
    45. [5, 10, 1, 3, 5, 9, 5, 21, 5, 1]
    46. >>> alist.remove(5) #删除数字5,从左向右开始删除
    47. >>> a = alist.pop()  #将pop的返回值赋值给a
    48. >>> a
    49. 1
    50. >>> b = alist.remove(5) # remove没有返回值,默认返回None
    51. >>> b
    52. >>> alist
    53. [10, 1, 3, 9, 5, 21, 5]
    54. >>> alist.reverse()
    55. >>> alist
    56. [5, 21, 5, 9, 3, 1, 10]
    57. >>> alist.sort() #默认升序
    58. >>> alist
    59. [1, 3, 5, 5, 9, 10, 21]
    60. >>> alist
    61. [1, 3, 5, 5, 9, 10, 21]
    62. >>> alist.sort(reverse=True) #降序
    63. >>> alist
    64. [21, 10, 9, 5, 5, 3, 1]
    65. >>> blist = alist.copy() #将alist的值赋值给blist, 但是采用不同内存空间
    66. >>> alist
    67. [21, 10, 9, 5, 5, 3, 1]
    68. >>> blist
    69. [21, 10, 9, 5, 5, 3, 1]
    70. >>> blist.clear() #清空列表
    71. >>> blist
    72. []
    73. >>> alist
    74. [21, 10, 9, 5, 5, 3, 1]

    列表练习: 

    1.程序的运行方式

    1. 1. 程序的运行方式
    2. ```shell
    3. (0) 压栈
    4. (1) 出栈
    5. (2) 查询
    6. (3) 退出
    7. 请选择(0/1/2/3): abc
    8. 无效的输入,请重试。
    9. (0) 压栈
    10. (1) 出栈
    11. (2) 查询
    12. (3) 退出
    13. 请选择(0/1/2/3): 2
    14. []
    15. (0) 压栈
    16. (1) 出栈
    17. (2) 查询
    18. (3) 退出
    19. 请选择(0/1/2/3): 0
    20. 数据:
    21. 输入为空
    22. (0) 压栈
    23. (1) 出栈
    24. (2) 查询
    25. (3) 退出
    26. 请选择(0/1/2/3): 0
    27. 数据: hello
    28. (0) 压栈
    29. (1) 出栈
    30. (2) 查询
    31. (3) 退出
    32. 请选择(0/1/2/3): 0
    33. 数据: world
    34. (0) 压栈
    35. (1) 出栈
    36. (2) 查询
    37. (3) 退出
    38. 请选择(0/1/2/3): 2
    39. ['hello', 'world']
    40. (0) 压栈
    41. (1) 出栈
    42. (2) 查询
    43. (3) 退出
    44. 请选择(0/1/2/3): 1
    45. 从栈中弹出了: world
    46. (0) 压栈
    47. (1) 出栈
    48. (2) 查询
    49. (3) 退出
    50. 请选择(0/1/2/3): 1
    51. 从栈中弹出了: hello
    52. (0) 压栈
    53. (1) 出栈
    54. (2) 查询
    55. (3) 退出
    56. 请选择(0/1/2/3): 1
    57. 空栈
    58. (0) 压栈
    59. (1) 出栈
    60. (2) 查询
    61. (3) 退出
    62. 请选择(0/1/2/3): 3
    63. Bye-bye
    64. ```
    65. 2. 框架
    66. ```python
    67. def push_it():
    68. def pop_it():
    69. def view_it():
    70. def show_menu():
    71. if __name__ == '__main__':
    72.     show_menu()
    73. ```
    74. 3. 完成每个函数

    2.程序代码

    初步代码到完善代码。

    1. stack = []
    2. def push_it():
    3.     data = input('数据: ').strip()
    4.     if data :  #非空字符串为真
    5.         stack.append(data)
    6.     else:
    7.         print('\033[31;1m输入为空\033[0m')
    8. def pop_it():
    9.     if stack : #列表非空为真
    10.         print('从栈中弹出了: \033[34;1m%s\033[0m' % stack.pop())
    11.     else:
    12.         print('\033[31;1m空栈\033[0m')
    13. def view_it():
    14.     print('\033[31;1m%s\033[0m' % stack)
    15. def show_menu():
    16. #    try:
    17.     menu = """(0)压栈:
    18. (1)出栈:
    19. (2)查询:
    20. (3)退出:
    21. 请选择(0/1/2/3):"""
    22.     while 1:
    23.         choice = input(menu).strip()#去除两端空白
    24.         if choice not in ['0','1','2','3']:
    25.             print('无效的输入,请重试: ')
    26.             continue
    27.         if choice == '0':
    28.             push_it()
    29.         elif choice == '1':
    30.             pop_it()
    31.         elif choice == '2':
    32.             view_it()
    33.         else:
    34.             break
    35.             print('bye-bye')
    36.     # except:
    37.     #     print('请按照菜单输入相应数字')
    38. if __name__ == '__main__':
    39.     show_menu()
    40. stack = []
    41. def push_it():
    42.     data = input('数据: ').strip()
    43.     if data :  #非空字符串为真
    44.         stack.append(data)
    45.     else:
    46.         print('\033[31;1m输入为空\033[0m')
    47. def pop_it():
    48.     if stack : #列表非空为真
    49.         print('从栈中弹出了: \033[34;1m%s\033[0m' % stack.pop())
    50.     else:
    51.         print('\033[31;1m空栈\033[0m')
    52. def view_it():
    53.     print('\033[31;1m%s\033[0m' % stack)
    54. def show_menu():
    55. #    try:
    56.     #cmds = {'0':push_it(),'1':pop_it(),'2':view_it()} ----把函数的值(返回值None)放到字典里
    57.     cmds = {'0':push_it,'1':pop_it,'2':view_it}  #这才是调用函数
    58.     menu = """(0)压栈:
    59. (1)出栈:
    60. (2)查询:
    61. (3)退出:
    62. 请选择(0/1/2/3):"""
    63.     while 1:
    64.         choice = input(menu).strip()#去除两端空白
    65.         if choice not in ['0','1','2','3']:
    66.             print('\033[031;1m无效的输入,请重试: \033[0m')
    67.             continue
    68.         if choice == '3':
    69.             print('bye-bye')
    70.             break
    71.         cmds[choice]()
    72.     # except:
    73.     #     print('请按照菜单输入相应数字')
    74. if __name__ == '__main__':
    75.     show_menu()

    元组:

    • 属于容器,不可变,序列

    创建元组:

    1. >>> 'hello'.count('l')
    2. 2
    3. >>> 'hello'.index('l')
    4. 2
    5. >>> atuple = (12, 20, 16, 25,22)
    6. >>> atuple.count(12)
    7. 1
    8. >>> atuple.index(12)
    9. 0
    10. #单元组
    11. >>> a = ('hello')
    12. >>> type(a)
    13. <class 'str'>
    14. >>> a
    15. 'hello'
    16. >>> b = ('hello',) #加逗号为了将其变成元组
    17. >>> type(b)
    18. <class 'tuple'>
    19. >>> b
    20. ('hello',)
    21. >>> len(b)
    22. 1

    字典:

    • 属于容器,可变,映射类型

    • 字典的键不能重复

    • 字典的key只能是不可变的 ---数字,字符,元组

    创建字典:

    1. >>> dict(['ab','cd','ef'])
    2. {'a': 'b', 'c': 'd', 'e': 'f'}
    3. >>> dict([('name','tom'),('age',20)])
    4. {'name': 'tom', 'age': 20}
    5. >>> dict([['name','tom'],['age',20]])
    6. {'name': 'tom', 'age': 20}
    7. >>> dict(['ab' ,['name','tom'],('age',20)])
    8. {'a': 'b', 'name': 'tom', 'age': 20}
    9. >>> {}.fromkeys(('tom','jerry','bob','alice'),7)
    10. {'tom': 7, 'jerry': 7, 'bob': 7, 'alice': 7}
    11. >>> adict = dict(['ab', ['name', 'tom'], ('age', 20)]) ---
    12. >>> adict
    13. {'a': 'b', 'name': 'tom', 'age': 20}
    14. >>> 'tom' in adict
    15. False
    16. >>> 'name' in adict
    17. True
    18. >>> for key in adict:
    19. ...     print(key, adict[key])
    20. ...
    21. a b
    22. name tom
    23. age 20
    24. >>> '%s is %s years old' % (adict['name'],adict['age'])
    25. 'tom is 20 years old'
    26. >>> '%(name)s is %(age)s years old' % adict
    27. 'tom is 20 years old'
    28. >>> adict['age'] = 22  #键存在,则更新值
    29. >>> adict
    30. {'a': 'b', 'name': 'tom', 'age': 22}
    31. >>> adict['email'] = '163@qq.com' #键不存在,则创建添加
    32. >>> adict
    33. {'a': 'b', 'name': 'tom', 'age': 22, 'email': '163@qq.com'}
    34. >>> del adict['a'] #删除字典中的键
    35. >>> adict
    36. {'name': 'tom', 'age': 22, 'email': '163@qq.com'}
    37. #元组可以作为key,列表不行,因为列表可变
    38. >>> {(10,15):'tom'}
    39. {(10, 15): 'tom'}
    40. #通过key获取值------用得最广泛最重要的
    41. >>> adict.get('name')
    42. 'tom'
    43. >>> adict.get('names', 'not found')#key不存在返回后者
    44. 'not found'
    45. >>> adict.keys()
    46. dict_keys(['name', 'age', 'email'])
    47. >>> adict.values()
    48. dict_values(['tom', 22, '163@qq.com'])
    49. >>> adict.items()
    50. dict_items([('name', 'tom'), ('age', 22), ('email', '163@qq.com')])
    51. >>> adict.pop('name') #弹出字典key
    52. 'tom'
    53. >>> adict.update({'age':23})
    54. >>> adict
    55. {'age': 23, 'email': '163@qq.com', 'name': 'tom'}

    集合:

    • 不同元素组成

    • 元素不能重复

    • 元素必须是不可变对象

    • 元素没有顺序

    • 集合就像是一个无值的字典

    • 分类:可变集合set,不可变集合frozenset

    1. #创建集合
    2. >>> aset = set('abcd')
    3. >>> aset
    4. {'d', 'c', 'a', 'b'}
    5. >>> set(['tom','jerry','bob'])
    6. {'tom', 'bob', 'jerry'}
    7. >>> bset = set('bcd')
    8. >>> bset
    9. {'d', 'c', 'b'}
    10. >>> 'a' in bset
    11. False
    12. >>> len(aset)
    13. 4
    14. >>> for ch in aset:
    15. ...     print(ch)
    16. ...
    17. d
    18. c
    19. a
    20. b
    21. >>> aset & bset  #交集
    22. {'d', 'c', 'b'}
    23. >>> aset | bset   #并集
    24. {'c', 'a', 'd', 'b'}
    25. >>> aset - bset   #差补,aset有,bset中没有的
    26. {'a'}
    27. >>> cset = set('abc')
    28. >>> cset.add('hello') ---添加
    29. >>> cset
    30. {'c', 'a', 'hello', 'b'}
    31. >>> cset.update('hello')---相当于列表extend添加
    32. >>> cset
    33. {'c', 'a', 'e', 'hello', 'h', 'l', 'b', 'o'}
    34. >>> cset.update(['nimade','chishi'])
    35. >>> cset
    36. {'x', 'c', 'a', 'hello', 'h', 'l', 'b', 'o', 'nimade', 'chishi', 'i'}
    37. >>> cset.remove('e')
    38. >>> cset
    39. {'c', 'a', 'hello', 'h', 'l', 'b', 'o'}
    40. >>> cset
    41. {'c', 'a', 'e', 'b', 'd'}
    42. >>> dset
    43. {'d', 'c', 'b'}
    44. >>> cset.issuperset(dset)---c是d的超集(包含)
    45. True
    46. >>> dset.issubset(cset)  ----d是c的子集
    47. True

    字典练习:

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

    1. ##去重##
    2. # [root@room9pc01 local.d]# cp /etc/passwd /tmp/mima1
    3. # [root@room9pc01 local.d]# cp /etc/passwd /tmp/mima2
    4. # [root@room9pc01 local.d]# vim /tmp/mima2
    5. # >>> with open('/tmp/mima1') as f1:
    6. # ...     aset = set(f1)
    7. # >>> with open('/tmp/mima2') as f2:
    8. # ...     bset = set(f2)
    9. # >>> bset - aset
    10. # >>> with open('/tmp/result.txt' , 'w' ) as f3:
    11. # ...     f3.writelines(bset - aset)

    数据类型结构练习

    模拟用户登录信息系统:

    1. import getpass
    2. userdb = {}
    3. def register():
    4.     username = input('用户名: ').strip()
    5.     if not username:
    6.         print('用户名不能为空')
    7.     elif username in userdb:
    8.         print('用户已存在')
    9.     else:
    10.         password = input('密码: ')
    11.         userdb[username] =password
    12. def login():
    13.     username = input('用户名: ').strip()
    14.     password = getpass.getpass('密码: ')
    15.     #if (username in userdb) and (userdb[username] == password):
    16.     if userdb.get(username) == password:
    17.         print('登录成功')
    18.     else:
    19.         print('登录失败')
    20. def show_menu():
    21.     cmds = {'0':register, '1':login}
    22.     menu = """(0) 注册
    23. (1) 登录
    24. (2) 退出
    25. 请选择(0/1/2): """
    26.     while 1:
    27.         choice = input(menu).strip()
    28.         if choice not in ['0','1','2']:
    29.             print('请输入提示信息,谢谢')
    30.             continue
    31.         if choice == '2' :
    32.             print('bye-bye')
    33.             break
    34.         cmds[choice]()
    35. if __name__ == '__main__':
    36.     show_menu()

     python基础篇总结 

    到这里,python基础篇算是完结了,大家可以反复去练习这几篇python基础篇,把基础打牢了,后面进行编程就会事半功倍,记得多敲,记得多敲,记得多敲!!!重要事情说三次。

  • 相关阅读:
    kali linux实现arp攻击对方主机
    Web缓存服务——Squid代理服务器
    基于AERMOD模型在大气环境影响评价中的实践技术应用
    坦克大战游戏开发中的设计模式总结
    Redis面试题
    开源|HDR-ISP开源项目介绍
    神经网络算法图像识别,神经网络算法图怎么看
    国产理想二极管控制器SCT53600,可替代TI的LM74700
    文件打包后输出 - Java实现
    消息队列的模拟实现(二)
  • 原文地址:https://blog.csdn.net/zerotoall/article/details/132805722