python16 3.11新特性,结构模式匹配 , 字典合并 ,同步迭代

3.11新特性,结构模式匹配 , 字典合并 ,同步迭代
match-case 语句 和其他语言的 switch-case 语句类似
用作多条件的分支选择。在 Python 中,case 关键词的后面叫做模式(pattern)
匹配字面值

代码1

# 结构模式匹配
score = input('请输入成绩等级:')
match score:
    case 'A':
        print('优秀')
    case 'B':
        print('良好')
    case 'C':
        print('及格')
    case 'D':
        print('不及格')
    case _:
        print('都不匹配')
print('---------------------------------------')

sex = int(input('请输入性别(1:男,0:女)'))
match sex:
    case 0:
        print('你好:美女。')
    case 1:
        print('Hello,帅哥')
    case _:
        print('未知性别')

代码2

# 字典合并
dict1 = {'a':10,'b':20}
dict2 = {'c':30,'d':40,'e':50}
merged_dict = dict1 | dict2
print(f'字典合并:{merged_dict}')

# 同步迭代
# 集合是无序的要注意输出的结果
print('同步迭代->集合是无序的')
fruits = {'apple','orange','pear','grape'}
counts = [10,3,4,5]
for f,c in zip(fruits,counts):
    match f,c:
        case 'apple',10:
            print('同步迭代->集合是无序的->10个苹果')
        case 'orange',3:
            print('同步迭代->集合是无序的->3个桔子')
        case 'pear',4:
            print('同步迭代->集合是无序的->4个梨')
        case 'grape',5:
            print('同步迭代->集合是无序的->5串葡萄')

# 列表是有序的
print('同步迭代->列表是有序的')
fruits1 = ['apple','orange','pear','grape']
counts1 = [10,3,4,5]
for f1,c1 in zip(fruits1,counts1):
    match f1,c1:
        case 'apple',10:
            print('同步迭代->列表是有序的->10个苹果')
        case 'orange',3:
            print('同步迭代->列表是有序的->3个桔子')
        case 'pear',4:
            print('同步迭代->列表是有序的->4个梨')
        case 'grape',5:
            print('同步迭代->列表是有序的->5串葡萄')

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

StevenChen85

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值