python过滤

基础 (The Basics)

Map, filter and reduce are functions that help you handle all kinds of collections. They are at the heart of modern technologies such as Spark and various other data manipulation and storage frameworks. But they can also very powerful helpers when working with vanilla Python.

映射,过滤和归约是可以帮助您处理各种集合的函数。 它们是诸如Spark和其他各种数据处理和存储框架之类的现代技术的核心。 但是在使用香草Python时,他们也可以提供非常强大的帮助。

地图 (Map)

Map is a function that takes as an input a collection e.g. a list [‘bacon’,’toast’,’egg’] and a function e.g. upper(). Then it will move every element of the collection through this function and produce a new collection with the same count of elements. Let’s look at an example

Map是一个函数,它以一个集合作为输入,例如列表['bacon','toast','egg']和一个函数(例如upper())作为输入。 然后它将通过此​​函数移动集合的每个元素,并产生一个具有相同元素计数的新集合。 让我们看一个例子

map_obj = map(str.upper,['bacon','toast','egg'])print(list(map_obj))>>['BACON', 'TOAST', 'EGG']

What we did here is use the map(some_function, some_iterable) function combined with the upper function (this function capitalizes each character of a string). As we can see we produced for every element in the input list another element in the output list. We receive always the same amount of elements in the output as we will put into it! Here we send 3 in and received 3 out, this is why we call it an N to N function. Let’s look at how one can use it.

我们在这里所做的是将map(some_function,some_iterable)函数与上层函数结合使用(该函数将字符串的每个字符大写)。 如我们所见,我们为输入列表中的每个元素生成了输出列表中的另一个元素。 我们在输出中始终收到与输入相同数量的元素! 在这里,我们发送3 in并接收3 out,这就是为什么我们称其为N对N函数。 让我们看看如何使用它。

def count_letters(x):    return len(list(x))map_obj = map(count_letters,['bacon','toast','egg'])print(list(map_obj))>>[6, 5, 3]

In this example we defined our own function count_letters(). The collection was passed through the function and in the output we have the amount of letters of each string! Let’s make this a little bit sexier using a lambda expression.

在此示例中,我们定义了自己的函数count_letters()。 集合通过函数传递,在输出中,我们有每个字符串的字母数量! 让我们使用lambda表达式使它更性感。

map_obj = map(lambda x:len(list(x)),['bacon','toast','egg'])print(list(map_obj))>>[6, 5, 3]

A lambda expression is basically just a short hand notation for defining a function. If you are not familiar with them you can check out how they work here. However, it should be fairly easy to understand how they work from the following examples.

Lambda表达式基本上只是用于定义函数的简写形式。 如果您不熟悉它们,可以在这里查看它们的工作方式。 但是,从以下示例中很容易理解它们的工作原理。

过滤 (Filter)

In contrast to Map, which is a N to N function. Filter is a N to M function where N≥M. What this means is that it reduces the number of elements in the collection. In other words, it filters them! As with map the notation goes filter(some_function, some_collection). Let’s check this out with an example.

与Map相反,后者是N对N的函数。 过滤器是N到M的函数,其中N≥M。 这意味着它减少了集合中元素的数量。 换句话说,它过滤了它们! 与map一样,符号使用filter(some_function,some_collection)。 我们来看一个例子。

def has_the_letter_a_in_it(x):    return 'a' in x# Let's first check out what happens with mapmap_obj = map(has_the_letter_a_in_it,['bacon','toast','egg'])print(list(map_obj))>>[True,True,False]# What happens with filter?map_obj = filter(has_the_letter_a_in_it,['bacon','toast','egg'])print(list(map_obj))>>['bacon', 'toast']

As we can see it reduces the number of elements in the list. It does so by calculating the return value for the function has_the_letter_a_in_it() and only returns the values for which the expression returns True.

如我们所见,它减少了列表中的元素数量。 它通过计算函数has_the_letter_a_in_it()的返回值来实现,并且仅返回表达式返回True的值

Again this looks much sexier using our all-time favorite lambda!

再次使用我们一直以来最喜欢的lambda看起来更性感!

map_obj = filter(lambda x: 'a' in x, ['bacon','toast','egg'])print(list(map_obj))>>['bacon', 'toast']

减少 (Reduce)

Let’s meet the final enemy and probably the most complicated of the 3. But no worries, it is actually quite simple. It is a N to 1 relation, meaning no matter how much data we pour into it we will get one result out of it. The way it does this is by applying a chain of the function we are going to pass it. Out of the 3 it is the only one we have to import from the functools. In contrast to the other two it can most often be found using three arguments reduce(some_function, some_collection, some_starting_value), the starting value is optional but it is usually a good idea to provide one. Let’s have a look.

让我们遇到最后的敌人,也许是最复杂的3个敌人但是不用担心,这实际上很简单。 这是N对1的关系,这意味着无论我们注入多少数据,我们都将从中得到一个结果。 它的实现方式是通过应用一系列函数来传递它。 在这3个中,这是我们必须从functools导入的唯一一个。 与其他两个相比,通常可以使用三个参数reduce(some_function,some_collection,some_starting_value)来找到它,起始值是可选的,但是通常最好提供一个。 我们来看一下。

from functools import reducemap_obj = reduce(lambda x,y: x+" loves "+y, ['bacon','toast','egg'],"Everyone")print(map_obj)>>'Everyone loves bacon loves toast loves egg'

As we can see we had to use a lambda function which takes two arguments at a time, namely x,y. Then it chains them through the list. Let’s visualize how it goes through the list

正如我们所看到的,我们必须使用一个lambda函数,该函数一次需要两个参数,即x,y。 然后,将它们链接通过列表。 让我们看一下它如何遍历列表

  1. x=“Everyone”, y=”bacon”: return ”Everyone loves bacon“x =“所有人”,y =“培根”:返回“每个人都喜欢培根”
  2. x=”Everyone loves bacon“, y=”toast”: return ”Everyone loves bacon loves toast“x =“每个人都喜欢培根”,y =“吐司”:返回“每个人都喜欢烟肉爱烤面包”
  3. x=”Everyone loves bacon loves toast“, y=”egg” : return ”Everyone loves bacon loves toast loves eggs“x =“每个人都爱培根爱烤面包”,y =“蛋”:返回“每个人都爱培根爱烤面包爱鸡蛋”

So we have our final element ”Everyone loves bacon loves toast loves eggs“. Those are the basic concepts to move with more ease through your processing pipeline. One honorable mention here is that you can not in every programming language assume that the reduce function will handle the element in order, e.g. in some languages it could be “‘Everyone loves egg loves toast loves bacon’”.

因此,我们有最后一个要素“每个人都爱培根,爱吐司,爱鸡蛋”。 这些是在处理管道中轻松移动的基本概念。 这里值得一提的是,您不能在每种编程语言中都假定reduce函数将按顺序处理元素,例如,在某些语言中,它可能是“'每个人都爱鸡蛋爱烤面包爱培根'”。

结合 (Combine)

To make sure we understood the concepts let’s use them together and build a more complex example.

为了确保我们理解这些概念,让我们一起使用它们并构建一个更复杂的示例。

from functools import reducevals = [0,1,2,3,4,5,6,7,8,9]# Let's add 1 to each element >> [1,2,3,4,5,6,7,8,9,10]map_obj = map(lambda x: x+1,vals)# Let's only take the uneven ones >> [1, 3, 5, 7, 9]map_obj = filter(lambda x: x%2 == 1,map_obj)# Let's reduce them by summing them up, ((((0+1)+3)+5)+7)+9=25map_obj = reduce(lambda x,y: x+y,map_obj,0)print(map_obj)>> 25

As we can see we can build pretty powerful things using the combination of the 3. Let’s move to one final example to illustrate what this might be used for in practice. To do so we load up a small subset of a dataset and will print the cities which are capitals and have more than 10 million inhabitants!

正如我们所看到的,我们可以使用3的组合来构建功能强大的东西。让我们来看一个最后的示例,以说明这在实践中可能会用到什么。 为此,我们加载了数据集的一小部分,并将打印首都和人口超过一千万的城市!

from functools import reduce#Let's define some datadata=[['Tokyo', 35676000.0, 'primary'], ['New York', 19354922.0, 'nan'], ['Mexico City', 19028000.0, 'primary'], ['Mumbai', 18978000.0, 'admin'], ['São Paulo', 18845000.0, 'admin'], ['Delhi', 15926000.0, 'admin'], ['Shanghai', 14987000.0, 'admin'], ['Kolkata', 14787000.0, 'admin'], ['Los Angeles', 12815475.0, 'nan'], ['Dhaka', 12797394.0, 'primary'], ['Buenos Aires', 12795000.0, 'primary'], ['Karachi', 12130000.0, 'admin'], ['Cairo', 11893000.0, 'primary'], ['Rio de Janeiro', 11748000.0, 'admin'], ['Ōsaka', 11294000.0, 'admin'], ['Beijing', 11106000.0, 'primary'], ['Manila', 11100000.0, 'primary'], ['Moscow', 10452000.0, 'primary'], ['Istanbul', 10061000.0, 'admin'], ['Paris', 9904000.0, 'primary']]map_obj = filter(lambda x: x[2]=='primary' and x[1]>10000000,data)map_obj = map(lambda x: x[0], map_obj)map_obj = reduce(lambda x,y: x+", "+y, map_obj, 'Cities:')print(map_obj)>> Cities:, Tokyo, Mexico City, Dhaka, Buenos Aires, Cairo, Beijing, Manila, Moscow

翻译自: https://towardsdatascience.com/accelerate-your-python-list-handling-with-map-filter-and-reduce-d70941b19e52

python过滤


http://www.taodudu.cc/news/show-2752477.html

相关文章:

  • scdl matlab,5自由度移动机器人的建模与仿真-硕士论文
  • redis 基础数据类型及应用 1
  • 深入理解安卓异步任务AsyncTask
  • LayoutTransiton实现简单的录制按钮
  • JavaScript权威指南7(四) 第十一章 JavaScript 标准库
  • BUU刷题记8
  • 分页插件中关于PageInfo
  • 【转载】分页插件中关于PageInfo
  • c打包html,cmake使用教程(十一)-使用cpack打包源码并编写自动化脚本上传到仓库...
  • java从入门到弃坑十五天
  • anaconda 和Tensorflow 2 安装
  • 实验三 mysql数据库与表的创建_实验二 数据库和表的创建与管理
  • Wannafly挑战赛29-御坂美琴(递归模拟)
  • Windows 2016 server NVIDIA cuda toolkit11.3 pytorch-gpu 踩坑教程
  • Homebrew进阶使用教程(二)-用一个命令行天气客户端构建自己的仓库
  • java 消息总线 框架_JavaWeb 消息总线框架 Saka V0.0.1 发布
  • Firefox修改快捷键插件SakaKey使用教程
  • 二叉树线索化(C语言)
  • VS2017编译SQLite3生成.lib
  • Python 图像文本识别 EasyOCR
  • 万维钢:秘密项目
  • 万维钢:我怎样管理信息
  • 《未来简史(下)》万维钢解读
  • #书籍《量子力学》读后感
  • 【21天习惯养成记~~day17晚】
  • 又订阅了万维刚的精英日课
  • 2016-2019 书单
  • 万维钢解读,从数学上解释为什么绝大多数投资者都会输给市场?最可能值,远远小于平均值...
  • 个人日记-《学习究竟是什么》读后感-2020/6/21
  • 《精英日课》第三季_2019年四月新书《九个工作谎言》_1工作是具体的,公司是虚拟的

python过滤_在纯Python中映射,过滤和减少相关推荐

  1. python竞赛_浅谈Python在信息学竞赛中的运用及Python的基本用法

    浅谈Python在信息学竞赛中的运用及Python的基本用法 前言 众所周知,Python是一种非常实用的语言.但是由于其运算时的低效和解释型编译,在信息学竞赛中并不用于完成算法程序.但正如LRJ在& ...

  2. python 偏函数_详细介绍Python中的偏函数

    机器学习实战之Logistic回归 本文来自云栖社区官方钉群"Python技术进阶",了解相关信息可以关注"Python技术进阶". 本系列教程特点: 基于&l ...

  3. php运行python爬虫_群晖系统中运行python爬虫程序

    重要:本文最后更新于2021-01-28 17:02:43,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗. 准备入手一台NAS,事先的学习是必须的,今天在VM虚拟机中安装好NAS后, ...

  4. qt如何用python结合_在Qt(C++)中与Python混合编程

    一.PythonQt库 在Qt(C++)中与Python混合编程,可以使用PythonQt库. 网站首页:http://pythonqt.sourceforge.net 下载页面:https://so ...

  5. sublime怎么配置python环境_在Sublime Editor中配置Python环境的详细教程

    导语在工作场景遇到了这么一个场景,就是需要定期去执行一个缓存接口,用于同步设备配置.首先想到的就是Linux上的crontab,可以定期,或者间隔一段时间去执行任务.但是如果你想要 2020-12-1 ...

  6. spyder python 使用_如何在spyder中使用vpython?

    我试着用vpython,无论如何,但我失败了...在 首先,我在win8.1上安装了anacondapython2.7.10. 然后,我通过在命令行中输入以下命令来安装Vpython: conda安装 ...

  7. 查看python包_怎么查看python中已安装的包

    展开全部 使用命令 pip list 可以查看2113python中已安装的包5261:具体步骤如下: 1.打开4102python:在命令符模式下(运1653行→cmd)输入Python回车即可 2 ...

  8. vscode怎么安装python库_如何在vscode中安装python库的方法步骤

    免费资源网 - https://freexyz.cn/ vscode安装python库 1.已经在vscode中装了python并配置好python运行环境. 检查是否正确配置好运行环境,按Windo ...

  9. python 切片_全面解读Python高级特性切片

    大家好,欢迎来到Crossin的编程教室! 众所周知,我们可以通过索引值(或称下标)来查找序列类型(如字符串.列表.元组-)中的单个元素,那么,如果要获取一个索引区间的元素该怎么办呢? 切片(slic ...

最新文章

  1. go语言 html 模板语法,go语言快速入门:template模板
  2. android找工作 2019,2019年真的很难找工作吗?
  3. ORA-04031: Unable To Allocate 32 Bytes Of Shared Memory
  4. Jenkisn之JDK-MVN-ANT-GRADLE
  5. CodeForces - 1307C Cow and Message(思维)
  6. 推荐几个自己经常去的一些博客和网站
  7. LeetCode 2210. 统计数组中峰和谷的数量
  8. python-文件和流
  9. (一)源码下载,编译,安装
  10. c语言100块钱买100只鸡算法,JS计算输出100元钱买100只鸡问题的解决方法
  11. Bzoj 4147: [AMPPZ2014]Euclidean Nim(博弈)
  12. Matlab箱线图Boxplot横坐标x轴设置
  13. intptr_t 和 uintptr_t类型使用总结
  14. [远程桌面]程mstsc连接Windows Server2008 未安装任何音频输出设备 启用声音音频解决
  15. PS抠图方法[photoshop中文教程]
  16. Trustzone的一些理解
  17. 弱水三千,只取一瓢饮
  18. 网页游戏打击感实施要点
  19. 任天堂被黑了!早期游戏源码及设计图大批曝光,原来塞尔达传说还有个血腥版本?
  20. 阿里App支付服务端接口开发(含后台异步回调,退款)

热门文章

  1. 跨平台flutter- window与Android Studio环境配置
  2. 诺禾-数据库操作优化
  3. Hie with the Pie(Floyd+状压dp)
  4. 赛效:超级简历在线简历助手教您一键制作简历
  5. 【JavaWeb】火车票管理系统 (三)用户登录-03
  6. java rds 数据库_JDBC(java数据库连接)和阿里云RDS数据库
  7. 基于Swift的iOS应用程序开发:录音及播放声音
  8. 国风就是帅,会三板吗,看看新天吧
  9. 爬虫系列学习之爬取西瓜视频
  10. 编程列入高考-青少儿编程学习-Python那些事