Python入门之列表,元组,字典,集合

列表

  • 列表是有序,可变的数据类型
  • 列表中可以包含不同类型的对象
  • 列表可以由[]或工厂函数创建
  • 支持下标及切片操作

列表更新

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

元组

  • 通过()或工厂函数tuple()创建元组
  • 元组是有序的,不可变类型
  • 与列表相似,作用于列表的操作,绝大数也可以作用于元组
  • 元组相当于静态的列表
>>> 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. 需要支持压栈、出栈、查询功能
思路:
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()

字典

  • 字典属于: 容器,可变,映射
  • 字典的key不能重复
  • 字典的key必须是不可变类型
  • 通过{}操作符或dict()工厂方法创建字典
  • 通过fromkeys()创建具有相同key值的默认字典
>>> 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'] = 'bob@163.com'
>>> 'bob' in adict   # 'bob'不是字典的key值
False
>>> 'name' in adict
True
>>> adict
{'a': 'b', 'name': 'bob', 'age': 25, 'email': 'bob@163.com'}
>>> len(adict)
4

# 字典最常用的方法
>>> adict.get('name')
'bob'
>>> adict['lisis']     # 对应的key值在字典中不存在,报错
Traceback (most recent call last):
  File "<stdin>", 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, 'bob@163.com'])
>>> list(adict.values())
['b', 'bob', 25, 'bob@163.com']
# 取出所有的键值对
>>> list(adict.items())
[('a', 'b'), ('name', 'bob'), ('age', 25), ('email', 'bob@163.com')]
# 根据key弹出字典的一项
>>> adict.pop('a')
'b'
# 批量向字典加入数据
>>> adict.update({'qwe': '123456','qq': '123'})

案例

模拟用户登陆信息系统

  1. 支持新用户注册,新用户名和密码注册到字典中
  2. 支持老用户登陆,用户名和密码正确提示登陆成功
  3. 主程序通过循环询问进行何种操作,根据用户的选
    择,执行注册或是登陆操作
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 "<stdin>", 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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值