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

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

《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基础篇,把基础打牢了,后面进行编程就会事半功倍,记得多敲,记得多敲,记得多敲!!!重要事情说三次。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值