python中减少循环的3个内置函数

  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方法明显更加简洁,过程也不需要循环。

  1. zip ()

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

例如,如果每天在工作中使用它的话,当用户就有第一个属性时表示该事件的开始时间,当有第二个属性时表示该事件的结束时间。进一步想想,工作中总是需要计算事件之间的时间差的,而zip是迄今为止最简单的实现方法。
范例中创建了两个包含数字的列表,任务是对相应的元素求和:

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方法更简洁、更可读——这是读者学会后会终身受益的东西。
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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值