25

这3个高级Python函数,不能再被你忽略了!

 4 years ago
source link: http://mp.weixin.qq.com/s?__biz=MzI2NjkyNDQ3Mw%3D%3D&%3Bmid=2247491770&%3Bidx=2&%3Bsn=bf2bc619ea8f8f7c3af9e85c73c90216
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

EjyQZvZ.jpg!web

全文共 1657 字,预计学习时长 3 分钟

Q3I3Qzq.jpg!web

图片来源:Drew Beamer/Unsplash

Python其实也可以带来很多乐趣。 重新审视一些一开始并不被人们熟知的内置函数并没有想象中那么难,但为什么要这么做呢?今天,本文就来仔细分析3个在日常工作中或多或少都会用到、但是大部分时间都被忽略的Python函数。

虽然它们可能不会节省大量的时间(如果了解了背后的具体逻辑),但是会使代码看起来更简洁明了。 也许这听起来没什么大不了的,但长久来看,可以使读者受益匪浅。 从第一个函数开始吧!

MVnqYfv.jpg!web

1. map()

map()是一个内置的Python函数,用于将一个函数应用于元素序列(如列表或字典)。 它可能是进行数据操作的最简单易读的方法。

下面的示例旨在求出列表中数字的平方数。 首先,必须明确所使用的函数。 接下来,笔者展示并对比了使用map()和不使用map()的方法,即python和非python的方法。

nums = [1, 2, 3, 4, 5]# 

this function will calculate square

def square_num(x): 

return x**2

# non-pythonic approach

squares = []

for num in nums:

squares.append(square_num(num))

print('Non-Pythonic Approach: ', squares)

# pythonic approach

x = map(square_num, nums)

print('Pythonic Approach: ', list(x))

输出本质上是相同的,但python方法明显更加简洁,过程也不需要循环。

2. zip ()

iIreY3N.jpg!web

zip()是笔者最中意使用的函数之一。 它允许用户同时迭代两个或多个列表。 这个功能在处理日期和时间问题时都十分有用。

例如,如果每天在工作中使用它的话,当用户就有第一个属性时表示该事件的开始时间,当有第二个属性时表示该事件的结束时间。 进一步想想,工作中总是需要计算事件之间的时间差的,而zip是迄今为止最简单的实现方法。

范例中创建了两个包含数字的列表,任务是对相应的元素求和:

first = [1, 3, 8, 4, 9]

second = [2, 2, 7, 5, 8]

# Iterate over two or more list at the same time

for x, y in zip(first, second):

print(x + y)

这样既简单又干净。

3. filter()

filter()函数在某种程度上类似于map()函数——也是将一个函数应用于某个序列,不同之处在于filter()只返回值为True的元素。

在如下的示例中,笔者创建了一个任意数字列表和一个函数,如果该数字是偶数,该函数将返回到True。 同样,笔者将演示如何以非python和python方式执行该操作。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# Will return true if input number is even

def even(x):

return x % 2 == 0

# non-pythonic approach

even_nums = []

for num in numbers:

if even(num):

even_nums.append(num)

print('Non-Pythonic Approach: ', even_nums)

# pythonic approach

even_n = filter(even, numbers)

print('Pythonic Approach: ', list(even_n))

同样,python方法更简洁、更可读——这是读者学会后会终身受益的东西。

Nbqmy26.jpg!web

推荐阅读专题

mMby2iU.jpg!web

iYjIniQ.jpg!web

IjUZ322.jpg!web

jmyiMne.jpg!web

Nbqmy26.jpg!web

留言 点赞 发个朋友圈

我们一起分享AI学习与发展的干货

编译组: 陈曼芳、王努铱

相关链接:

https://towardsdatascience.com/3-advanced-python-functions-for-data-scientists-f869016da63a

如需转载,请后台留言,遵守转载规范

推荐文章阅读

ACL2018论文集50篇解读

EMNLP2017论文集28篇论文解读

2018年AI三大顶会中国学术成果全链接

ACL2017 论文集:34篇解读干货全在这里

10篇AAAI2017经典论文回顾

长按识别二维码可添加关注

读芯君爱你

2ABbUry.gif


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK