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

2023-11-17

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

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

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

《shell》:shell学习

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

《k8》暂未更新

《docker学习》暂未更新

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

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

《运维日常》运维日常

 

列表:

  • 属于容器,可变,序列

创建以及访问列表:

>>> 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]

列表练习: 

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
```
2. 框架
```python
def push_it():
def pop_it():
def view_it():
def show_menu():
if __name__ == '__main__':
    show_menu()
```
3. 完成每个函数

2.程序代码

初步代码到完善代码。

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 = []
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()

元组:

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

创建元组:

>>> '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)
<class 'str'>
>>> a
'hello'
>>> b = ('hello',) #加逗号为了将其变成元组
>>> type(b)
<class 'tuple'>
>>> b
('hello',)
>>> len(b)
1

字典:

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

  • 字典的键不能重复

  • 字典的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'] = '163@qq.com' #键不存在,则创建添加
>>> adict
{'a': 'b', 'name': 'tom', 'age': 22, 'email': '163@qq.com'}

>>> del adict['a'] #删除字典中的键
>>> adict
{'name': 'tom', 'age': 22, 'email': '163@qq.com'}

#元组可以作为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, '163@qq.com'])
>>> adict.items()
dict_items([('name', 'tom'), ('age', 22), ('email', '163@qq.com')])

>>> adict.pop('name') #弹出字典key
'tom'

>>> adict.update({'age':23})
>>> adict
{'age': 23, 'email': '163@qq.com', 'name': 'tom'}



集合:

  • 不同元素组成

  • 元素不能重复

  • 元素必须是不可变对象

  • 元素没有顺序

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

  • 分类:可变集合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)
... 
d
c
a
b

>>> aset & bset  #交集
{'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)

数据类型结构练习

模拟用户登录信息系统:

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()

 python基础篇总结 

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐

  • opencv4应用开发基础

    opencv3 0版本以上都是用C 实现的 常用的一些函数及类型集中在cv命名空间里 cv Mat类型用于表示一个图像 构造函数除了空的构造函数外 还有很多个 Mat int rows int cols int type 创建指定行 列数的
  • springcloud常见面试题(2023最新)

    目录 前言 一 微服务 1 微服务是什么 2 你知道哪些RPC框架 3 springCloud和Dubbo有什么区别 4 SpringCloud由什么组成 二 Spring Cloud Eureka 1 Eureka包含几个组件 2 Eur
  • 探究Android SQLite3多线程

    http www cnblogs com xyczero p 4096297 html 最近做项目时在多线程读写数据库时抛出了异常 这自然是我对SQlite3有理解不到位的地方 所以事后仔细探究了一番 关于getWriteableDataB
  • visio增加连接点

    在画系统架构图的时候遇到一个问题 如果一个图形本来有的连接点不够 需要在任何的位置上增加连接点 看了很多网络介绍 但是总是增加不成功 继续发现接下来问题揭晓 2013版本visio举例 首先在开始中找到连接点 其次 按住ctrl键 在想要添
  • CBOW 与 skip-gram

    skip gram是利用中间词预测邻近词 cbow是利用上下文词预测中间词 一 CBOW 1 continues bag of words 其本质是通过context来预测word CBOW之所以叫连续词袋模型 是因为在每个窗口内它也不考虑
  • Sublime Text自定义配色方案

    先推荐介绍几款非常好用的自定义主题 https github com aziz tmTheme Editor http tmtheme editor herokuapp com 这个可以在线修改配色方案 也可以上传本地的方案修改 https
  • linux源码文件数量,Linux 下统计文件夹大小及文件数量

    查看文件夹大小 lib 目录大小 du sh lib lib 子目录大小 du sh lib 查看 lib 目录下普通文件大小 find lib type f xargs ls la awk F BEGIN sum 0 sum 5 END
  • prim算法解决最小生成树问题

    刚好这次又遇到了prim算法 就做了下整理 可以参考 数据结构与算法分析c 描述 这本书 个人而言 很经典 并把以前写的代码也整理了一下 做下分享 同时也加深下自己的理解 prim算法是解决最小生成树问题的一个很好的算法 此算法是是将点集合
  • iOS - 常用的宏定义

    1 处理NSLog事件 开发者模式打印 发布者模式不打印 ifdef DEBUG define NSLog FORMAT fprintf stderr s d t s n NSString stringWithUTF8String FILE
  • 第九章 Qt拖放

    拖放是Qt实现的应用程序内或者多个应用程序之间传递信息的一种直观的现代操作方式 有没有想到windows的剪贴板 数据的移动和复制功能都异曲同工嘞 一 使拖放生效 拖放包含两个动作 拖动 和 放下 Qt窗口部件可以作为拖动点 drag si
  • NestedScrollView + RecyclerView完美解决显示不全及滑动冲突

  • color属性 python_Python cv2.CV_LOAD_IMAGE_COLOR属性代码示例

    需要导入模块 import cv2 as 别名 或者 from cv2 import CV LOAD IMAGE COLOR as 别名 def load cv2 img grayscale None TODO load images if
  • Hive连接报错,显示用户没有权限 org.apache.hadoop.ipc.RemoteException:User: xxx is not allowed to impersonate root

    Hive连接报错 显示用户没有权限 org apache hadoop ipc RemoteException User xxx is not allowed to impersonate root org apache hadoop ip
  • docker学习使用文档

    docker学习参考文档 学习途径 安装 介绍 环境准备 开始安装 卸载依赖 删除资源 阿里云镜像加速 底层原理 docker怎么工作 docker为什么比虚拟机快 1 docker有着比虚拟机更少的抽象层 2 docker利用的是宿主机内
  • 安卓ui开发教程下载!被面试官问的Android问题难倒了,内容太过真实

    前言 这些题目是网友去百度 小米 乐视 美团 58 猎豹 360 新浪 搜狐等一线互联网公司面试被问到的题目 熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率 欢迎一线公司员工以及网友提交面试题库 欢迎留言 网上的都是按照公司划分的
  • Linux实现多进程服务端Socket通信

    目录 程序流程 程序实例 运行结果 本例主要是让服务器能够同时处理多个客户端的连接请求 程序流程 1 创建基本的套接字 并绑定地址信息 设置监听 2 循环accept来接收连接请求 每接收一个连接请求 就创建一个子进程 3 在子进程中进行客
  • 浅谈人工智能专业,作为普通学生对未来的看法

    一 个人简介 本人是一个普通大学的普通学生 和大多数人一样 经历过高考志愿填报 在身边人的建议下 自己对于人工智能专业那听起来高大上的名字以及对于未知的探索渴望 我最终填报了人工智能专业 二 给普通学生的一段话 我真的和许许多多人一样就是一
  • Intel C and C++ Compilers: Features and Supported Platforms

    Submitted by Jennifer J Intel on April 20 2015 Share Tweet Share Intel C Compiler Features Supported in Different Produc
  • c++ 可变参数的三种实现方式

    c 可变参数 方法一 C语言的 va list1 include
  • 【python零基础入门学习】python基础篇(基础结束篇)之数据结构类型-列表,元组,字典,集合(五)

    本站以分享各种运维经验和运维所需要的技能为主 python零基础入门 python零基础入门学习 python运维脚本 python运维脚本实践 shell shell学习 terraform 持续更新中 terraform Aws学习零基