【Python基础篇】【14.推导式】列表推导式、元组推导式、字典推导式、集合推导式(附案例,源码)详解


推导式

推导式(comprehensions),又称解析式,是 Python 中常见的语法糖。推导式可以从一个数据序列构建另一个新的数据序列,常用于数据处理场景。

语法:表达式 for 迭代变量 in 可迭代对象 [if 条件表达式]

推导式的核心为 for 循环。根据返回对象的不同,推导式可区分为列表推导式,字典推导式,结合推导式等。不同推导式在语法上基本一致

列表推导式

python列表推导式,又称列表解析式。可以用一种简明扼要的方法来创建列表

''' 列表推导式 '''
result = [i for i in range(5)]  # 快速的创建列表
print(result)  # [0, 1, 2, 3, 4]

# 示例1 - 过滤掉长度小于或等于3的字符串列表,并将得到的字符串转换为大写字母
names = ['Bob', 'Tom', 'alice', 'Jerry', 'Wendy', 'Smith']
new_list = [name.upper() for name in names if len(name) > 3]
print(new_list)  # 输出结果 ['ALICE', 'JERRY', 'WENDY', 'SMITH']

# 示例2 - 从输入的字符串中过滤掉小于或等于3的字符串列表,将得到的字符串转换成小写字母,输入的多个字符串之间用空格隔开
new_list = [name.lower() for name in input('请输入要输入的字符串:').split() if
            len(name) > 3]  # 输入  TOM JACK JERRY MARY ALICE WENDY
print(new_list)  # 输出  ['jack', 'jerry', 'mary', 'alice', 'wendy']

# 示例3 -  计算30以内可以被3整除的整数,对得到的数据取平方值
new_list = [x * x for x in range(31) if x % 3 == 0]
print(new_list)  # [0, 9, 36, 81, 144, 225, 324, 441, 576, 729, 900]

# 示例4 - 从嵌套列表中去除偶数
list1 = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = [x for y in list1 for x in y if x % 2 == 0]
print(new_list)  # 输出 [2, 4, 6, 8]

# 示例5 - 双遍历字符并相加
new_list = [x + y for x in 'python' for y in '12']
print(new_list)  # 输出 ['p1', 'p2', 'y1', 'y2', 't1', 't2', 'h1', 'h2', 'o1', 'o2', 'n1', 'n2']

元组推导式

元组推导式可以利用range区间、元组、列表、字典和集合等数据类型,快速生成一个满足指定需求的元组

''' 元组推导式 '''
(表达式 for 变量 in iterable(可迭代对象))
(out_exp_res for out_exp in input_list)

(表达式 for 变量 in iterable(可迭代对象) if 条件)
(out_exp_res for out_exp in input_list if condition)

# 示例1 - 不使用tuple()转换,输出的是生成器对象
new_tuple = (x for x in range(31) if x % 2 == 0)
print(new_tuple)  # 输出 <generator object <genexpr> at 0x000001A8738FACF0>

# 示例2 - 使用tuple()转换为元组
new_tuple = (x for x in range(31) if x % 2 == 0)
print(tuple(new_tuple))  # 输出 (0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30)

字典推导式

字典推导式的格式与列表推导式格式类似,不同在于字典推导式使用大括号 {},且以键值对的格式输出,列表推导式使用方括号 [];字典推导式的返回值是字典。

''' 字典推导式 '''
a = {i: i for i in range(8)}
print(a)  # {0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7}

# 示例1 - 以10以内的偶数为键,数字的平方为值
new_dict = {x: x * x for x in range(11) if x % 2 == 0}
print(new_dict)  # 输出 {0: 0, 2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

# 示例2 - 以输入的字符串为键,以输入的字符串的长度为值
new_dict = {s: len(s) for s in input().split()}  # 输入 TOM JACK JERRY MARY ALICE WENDY
print(new_dict)  # 输出 {'TOM': 3, 'JACK': 4, 'JERRY': 5, 'MARY': 4, 'ALICE': 5, 'WENDY': 5}

集合推导式

集合是无序,不重复的,所以集合推导式得到的新序列也是无序,不重复的。集合推导式的格式和列表类似,区别在于集合使用大括号 {},列表使用方括号 []。

''' 集合推导式 '''
b = {i for i in range(8)}
print(b)  # {0, 1, 2, 3, 4, 5, 6, 7}

# 示例1 - 把字符串中的重复的字母去除
new_set = {x for x in 'aaasdfghfdsfg123323'}
print(new_set)  # 输出 {'s', '2', 'd', 'f', 'h', 'a', '1', 'g', '3'}

# 示例2 - 判断不是'abc'的字母并输出
new_set = {x for x in 'abcdsfabdcad' if x not in 'abc'}
print(new_set)  # 输出 {'f', 'd', 's'}

案例 - 推导式

import pprint
"""
请用列表推导式构建以下地址规律
    https://www.maoyan.com/board/4?offset=0
    https://www.maoyan.com/board/4?offset=10
    https://www.maoyan.com/board/4?offset=20
    https://www.maoyan.com/board/4?offset=30
    https://www.maoyan.com/board/4?offset=40
    https://www.maoyan.com/board/4?offset=50
    https://www.maoyan.com/board/4?offset=60
    https://www.maoyan.com/board/4?offset=70
    https://www.maoyan.com/board/4?offset=80
    https://www.maoyan.com/board/4?offset=90
请在下方编辑代码:
"""

result = [f'https://www.maoyan.com/board/4?offset={i}' for i in range(0, 91, 10)]
pprint.pprint(result)

案例 - 字典提取数据

"""
要求:从字典中提取歌手、歌名、音乐地址
"""
data = {
    'state': True,
    'errno': 22000,
    'errmsg': '',
    'elapsed_time': '0.0122',
    'data': {
        'artist': [
            {'artistCode': 'A10047720', 'birthday': '1983-07-17', 'gender': '男', 'name': '薛之谦', 'artistType': 38,
             'artistTypeName': '歌手',
             'pic': 'https://img01.dmhmusic.com/0101/M00/F8/AE/ChR45V7XEJWAZJ8KAAL8wj6aS4w115.jpg',
             'region': ''}],
        'cpId': 23,
        'pic': 'https://img01.dmhmusic.com/0412/M00/FE/96/ChAKEl_IzFiAUZyEAA-Q7DRXeIo850.jpg',
        'title': '你还要我怎样',
        'path': 'https://audio04.dmhmusic.com/71_53_T10038986648_128_4_1_0_sdk-cpm/cn/0208/M00/E5/61/ChR46119DrGAW4d4AEvErRDwLyg867.mp3?xcode=c1a597cce27ff185785e95c6cf346f934713ee4',
    }}

"""
要求以以下格式输出:
```
歌手: 薛之谦
歌名: 你还要我怎样
音乐地址: https://audio04.dmhmusic.com/71_53_T10038986648_128_4_1_0_sdk-cpm/cn/0208/M00/E5/61/ChR46119DrGAW4d4AEvErRDwLyg867.mp3?xcode=c1a597cce27ff185785e95c6cf346f934713ee4
```
最后点击一下音乐地址,你会发现一件神奇的事情 `φ(>ω<*)` 
"""
"""自己在下方编写代码实现功能"""

# 取歌手名
singer = data['data']['artist'][0]['name']
print(singer)  # 薛之谦

# 取歌名
song = data['data']['title']
print(song)  # 你还要我怎样

# 取歌曲的地址
address = data['data']['path']
print(address)

案例 - 统计单词次数

# -*- coding: utf-8 -*-
"""
统计Python之禅中所有**单词**(注意是单词)出现的次数
"""
# python 之禅
s = """
The Zen of Python, by Tim Peters
Beautiful is better than ugly
Explicit is better than implicit
Simple is better than complex
Complex is better than complicated
Flat is better than nested
Sparse is better than dense
Readability counts
Special cases aren't special enough to break the rules
Although practicality beats purity
Errors should never pass silently
Unless explicitly silenced
In the face of ambiguity, refuse the temptation to guess
There should be one-- and preferably only one --obvious way to do it
Although that way may not be obvious at first unless you're Dutch
Now is better than never
Although never is often better than *right* now
If the implementation is hard to explain, it's a bad idea
If the implementation is easy to explain, it may be a good idea
Namespaces are one honking great idea -- let's do more of those
"""

"""自己在下方编写代码实现功能"""

# 把字符串多余的字符给他去掉
result = s.replace(',', '').replace('-', '').replace('*', '')

# 通过 split 将字符串分割成一个列表,方便统计单词出现的次数
result1 = result.split()  # 默认以空白字符进行分隔

d = {}
for i in result1:
    if i not in d.keys():  # 如果这个元素不在字典的键里面
        d[i] = 1  # 表示他是第一次出现
    else:
        d[i] += 1

print(d)
# {'The': 1, 'Zen': 1, 'of': 3, 'Python': 1, 'by': 1, 'Tim': 1, 'Peters': 1, 'Beautiful': 1, 'is': 10, 'better': 8, 'than': 8, 'ugly': 1, 'Explicit': 1, 'implicit': 1, 'Simple': 1, 'complex': 1, 'Complex': 1, 'complicated': 1, 'Flat': 1, 'nested': 1, 'Sparse': 1, 'dense': 1, 'Readability': 1, 'counts': 1, 'Special': 1, 'cases': 1, "aren't": 1, 'special': 1, 'enough': 1, 'to': 5, 'break': 1, 'the': 5, 'rules': 1, 'Although': 3, 'practicality': 1, 'beats': 1, 'purity': 1, 'Errors': 1, 'should': 2, 'never': 3, 'pass': 1, 'silently': 1, 'Unless': 1, 'explicitly': 1, 'silenced': 1, 'In': 1, 'face': 1, 'ambiguity': 1, 'refuse': 1, 'temptation': 1, 'guess': 1, 'There': 1, 'be': 3, 'one': 3, 'and': 1, 'preferably': 1, 'only': 1, 'obvious': 2, 'way': 2, 'do': 2, 'it': 2, 'that': 1, 'may': 2, 'not': 1, 'at': 1, 'first': 1, 'unless': 1, "you're": 1, 'Dutch': 1, 'Now': 1, 'often': 1, 'right': 1, 'now': 1, 'If': 2, 'implementation': 2, 'hard': 1, 'explain': 2, "it's": 1, 'a': 2, 'bad': 1, 'idea': 3, 'easy': 1, 'good': 1, 'Namespaces': 1, 'are': 1, 'honking': 1, 'great': 1, "let's": 1, 'more': 1, 'those': 1}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Python推导是一种简洁的语法糖,可以从一个数据序列构建另一个新的数据序列。常见的推导包括列表推导式字典推导集合推导列表推导式可以通过对一个列表进行迭代和筛选操作,生成一个新的列表。字典推导可以通过对一个字典进行迭代操作,生成一个新的字典。而集合推导则可以通过对一个集合进行迭代和筛选操作,生成一个新的集合推导在数据处理场景中非常常见,并可以大大简化代码的编写和阅读。如果你想了解更多关于推导的语法和用法,请参考引用和引用中提供的链接。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Python推导简单示例【列表推导式字典推导集合推导】](https://download.csdn.net/download/weixin_38708361/12865890)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Python推导](https://blog.csdn.net/iprobobo/article/details/123582135)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

My.ICBM

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

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

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

打赏作者

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

抵扣说明:

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

余额充值